diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 0c85113914fb..c5674d4eccd9 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -7,11 +7,11 @@ Also please indicate in the issue title which language/library is concerned. Eg: -##### Swagger-codegen version +##### openapi-generator version - + -##### Swagger declaration file content or url +##### OpenAPI declaration file content or url + ##### Suggest a fix/enhancement diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index e84227bd6b59..e70e5527c124 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,9 +1,9 @@ ### PR checklist -- [ ] Read the [contribution guidelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md). +- [ ] Read the [contribution guidelines](https://github.com/wing328/openapi-generator/blob/master/CONTRIBUTING.md). - [ ] Ran the shell script under `./bin/` to update Petstore sample so that CIs can verify the change. (For instance, only need to run `./bin/{LANG}-petstore.sh` and `./bin/security/{LANG}-petstore.sh` if updating the {LANG} (e.g. php, ruby, python, etc) code generator or {LANG} client's mustache templates). Windows batch files can be found in `.\bin\windows\`. - [ ] Filed the PR against the correct branch: `3.0.0` branch for changes related to OpenAPI spec 3.0. Default: `master`. -- [ ] Copied the [technical committee](https://github.com/swagger-api/swagger-codegen/#swagger-codegen-technical-committee) to review the pull request if your PR is targeting a particular programming language. +- [ ] Copied the [technical committee](https://github.com/wing328/openapi-generator/#swagger-codegen-technical-committee) to review the pull request if your PR is targeting a particular programming language. ### Description of the PR diff --git a/.gitignore b/.gitignore index 6e435e8592d5..9e0a09473280 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,7 @@ out/ *.iws classpath.txt version.properties -!modules/swagger-codegen-cli/src/main/resources/version.properties +!modules/openapi-generator-cli/src/main/resources/version.properties .project .classpath lib/* diff --git a/.travis.yml b/.travis.yml index a032b34aef7d..ace09a914375 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ sudo: required language: java jdk: - - openjdk7 + - openjdk8 cache: directories: diff --git a/.travis.yml.ios b/.travis.yml.ios index 39882295a415..74772d17e97a 100644 --- a/.travis.yml.ios +++ b/.travis.yml.ios @@ -34,7 +34,7 @@ addons: before_install: - export SW=`pwd` - rvm list - - rvm use 2.3.0 + - rvm use 2.3.3 - gem environment - gem install bundler -N --no-ri --no-rdoc - gem install cocoapods -v 1.2.1 -N --no-ri --no-rdoc @@ -61,8 +61,6 @@ before_install: - xcpretty -v # show go version - go version - # show stack version - - stack --version script: # run integration tests defined in maven pom.xml diff --git a/README.md b/README.md index a45140b192c7..783430ff49c9 100644 --- a/README.md +++ b/README.md @@ -747,9 +747,11 @@ Please refer to this [page](https://github.com/swagger-api/swagger-codegen/blob/ Companies/Projects using Swagger Codegen ---------------------------------------- Here are some companies/projects using Swagger Codegen in production. To add your company/project to the list, please visit [README.md](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) and click on the icon to edit the page. +- [Acando](https://www.acando.de/) - [Accengage](https://www.accengage.com/) - [Accruent](https://www.accruent.com/) - [Activehours](https://www.activehours.com/) +- [Actonica](https://www.actonica.com) - [Acunetix](https://www.acunetix.com/) - [Atlassian](https://www.atlassian.com/) - [Autodesk](http://www.autodesk.com/) @@ -947,6 +949,7 @@ Presentations/Videos/Tutorials/Books - 2018/01/19 - [Generowanie kodu usług REST - przewodnik dla początkujących](https://gum.co/swagger_codegen_beginner_pl)(eBook) by [William Cheng](https://github.com/wing328), [Tomasz Prus](https://github.com/tomplus), [Bartek Kryza](https://github.com/bkryza) - 2018/02/03 - [Writing REST APIs with OpenAPI and Swagger Ada](https://www.slideshare.net/StephaneCarrez1/writing-rest-apis-with-openapi-and-swagger-ada/StephaneCarrez1/writing-rest-apis-with-openapi-and-swagger-ada) by [Stephane Carrez](https://github.com/stcarrez) at [FOSDEM 2018](https://fosdem.org/2018) - 2018/02/28 - [OpenAPI–An eBay Perspective](https://www.ebayinc.com/stories/blogs/tech/openapi-an-ebay-perspective/) by Shekhar Banerjee (eBay) +- 2018/03/16 - [REST APIのためのコード生成入門](https://gumroad.com/l/swagger_codegen_beginner_jp) by [William Cheng](https://github.com/wing328), [中野暁人](https://github.com/ackintosh), [和田拓朗](https://github.com/taxpon) # Swagger Codegen Core Team @@ -1079,7 +1082,7 @@ If you want to join the committee, please kindly apply by sending an email to wi | Android | @jaz-ah (2017/09) | | Apex | | | Bash | @frol (2017/07) @bkryza (2017/08) @kenjones-cisco (2017/09) | -| C++ | @ravinikam (2017/07) @stkrwork (2017/07) @fvarose (2017/11) @etherealjoy (2018/02) | +| C++ | @ravinikam (2017/07) @stkrwork (2017/07) @fvarose (2017/11) @etherealjoy (2018/02) @martindelille (2018/03) | | C# | @mandrean (2017/08) @jimschubert (2017/09) | | Clojure | | | Dart | @ircecho (2017/07) | @@ -1102,7 +1105,7 @@ If you want to join the committee, please kindly apply by sending an email to wi | Ruby | @cliffano (2017/07) @zlx (2017/09) | | Rust | @frol (2017/07) @farcaller (2017/08) @bjgill (2017/12) | | Scala | @clasnake (2017/07) @jimschubert (2017/09) @shijinkui (2018/01) @ramzimaalej (2018/03) | -| Swift | @jgavris (2017/07) @ehyche (2017/08) @Edubits (2017/09) @jaz-ah (2017/09) | +| Swift | @jgavris (2017/07) @ehyche (2017/08) @Edubits (2017/09) @jaz-ah (2017/09) @d-date (2018/03) | | TypeScript | @TiFu (2017/07) @taxpon (2017/07) @sebastianhaas (2017/07) @kenisteward (2017/07) @Vrolijkx (2017/09) @macjohnny (2018/01) | diff --git a/bin/cpprest-petstore.sh b/bin/cpprest-petstore.sh index 73d4c491e76f..1d4648f44d4e 100755 --- a/bin/cpprest-petstore.sh +++ b/bin/cpprest-petstore.sh @@ -26,6 +26,6 @@ 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/cpprest -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l cpprest -o samples/client/petstore/cpprest" +ags="generate -t modules/openapi-generator/src/main/resources/cpprest -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l cpp-restsdk -o samples/client/petstore/cpprest $@" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/flash-petstore.json b/bin/flash-petstore.json new file mode 100644 index 000000000000..c13ef7f06e78 --- /dev/null +++ b/bin/flash-petstore.json @@ -0,0 +1,4 @@ +{ + "packageName": "io.swagger", + "invokerPackage": "io.swagger" +} diff --git a/bin/flash-petstore.sh b/bin/flash-petstore.sh index cfb6f80de7c3..752ed2906b53 100755 --- a/bin/flash-petstore.sh +++ b/bin/flash-petstore.sh @@ -26,6 +26,6 @@ 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/flash -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l flash -o samples/client/petstore/flash" +ags="$@ generate -t modules/openapi-generator/src/main/resources/flash -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l flash -o samples/client/petstore/flash -c bin/flash-petstore.json" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-inflector-petstore-server.sh b/bin/java-inflector-petstore-server.sh index ee64ef74f690..67fed262a4cc 100755 --- a/bin/java-inflector-petstore-server.sh +++ b/bin/java-inflector-petstore-server.sh @@ -26,6 +26,6 @@ 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/JavaInflector -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l inflector -o samples/server/petstore/java-inflector -DhideGenerationTimestamp=true" +ags="$@ generate -t modules/openapi-generator/src/main/resources/JavaInflector -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java-inflector -o samples/server/petstore/java-inflector -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-msf4j-petstore-server.sh b/bin/java-msf4j-petstore-server.sh index b8e2a3e3bccc..abf6a838c567 100755 --- a/bin/java-msf4j-petstore-server.sh +++ b/bin/java-msf4j-petstore-server.sh @@ -26,7 +26,7 @@ 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/MSF4J -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l msf4j -o samples/server/petstore/java-msf4j/ -DhideGenerationTimestamp=true --additional-properties artifactId=swagger-msf4j-server" +ags="$@ generate -t modules/openapi-generator/src/main/resources/MSF4J -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java-msf4j -o samples/server/petstore/java-msf4j/ -DhideGenerationTimestamp=true --additional-properties artifactId=swagger-msf4j-server" echo "Removing files and folders under samples/server/petstore/java-msf4j/src/main" rm -rf samples/server/petstore/java-msf4j/src/main diff --git a/bin/java-play-framework-petstore-server-all.sh b/bin/java-play-framework-petstore-server-all.sh index 5ab911f11355..fa4fd9daf90e 100755 --- a/bin/java-play-framework-petstore-server-all.sh +++ b/bin/java-play-framework-petstore-server-all.sh @@ -9,3 +9,4 @@ ./bin/java-play-framework-petstore-server-no-wrap-calls.sh ./bin/java-play-framework-petstore-server-fake-endpoints.sh ./bin/java-play-framework-petstore-server-api-package-override.sh +./bin/java-play-framework-petstore-server-async.sh diff --git a/bin/java-play-framework-petstore-server-async.json b/bin/java-play-framework-petstore-server-async.json new file mode 100755 index 000000000000..69161a46d0f2 --- /dev/null +++ b/bin/java-play-framework-petstore-server-async.json @@ -0,0 +1,5 @@ +{ + "additionalProperties" : { + "supportAsync" : true + } +} diff --git a/bin/java-play-framework-petstore-server-async.sh b/bin/java-play-framework-petstore-server-async.sh new file mode 100755 index 000000000000..6534d94521fd --- /dev/null +++ b/bin/java-play-framework-petstore-server-async.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/openapi-generator/src/main/resources/JavaPlayFramework -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l java-play-framework -c bin/java-play-framework-petstore-server-async.json -o samples/server/petstore/java-play-framework-async -DhideGenerationTimestamp=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-undertow-petstore-server.sh b/bin/java-undertow-petstore-server.sh index ab1b472dcd38..b2851167117d 100755 --- a/bin/java-undertow-petstore-server.sh +++ b/bin/java-undertow-petstore-server.sh @@ -26,6 +26,6 @@ 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/undertow -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l undertow -o samples/server/petstore/undertow --additional-properties hideGenerationTimestamp=true" +ags="$@ generate -t modules/openapi-generator/src/main/resources/undertow -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l java-undertow-server -o samples/server/petstore/undertow --additional-properties hideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-cxf-client-petstore.sh b/bin/jaxrs-cxf-client-petstore.sh index 3ad02bccb004..90e8a8c3978b 100755 --- a/bin/jaxrs-cxf-client-petstore.sh +++ b/bin/jaxrs-cxf-client-petstore.sh @@ -26,6 +26,6 @@ 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 "jaxrs-cxf-petstore-client" -t modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/ -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf -o samples/client/petstore/jaxrs-cxf-client/" +ags="$@ generate --artifact-id "jaxrs-cxf-petstore-client" -t modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/ -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf-client -o samples/client/petstore/jaxrs-cxf-client/" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-jersey1-petstore-server.sh b/bin/jaxrs-jersey1-petstore-server.sh index 92fbface611f..ccef71e3d93d 100755 --- a/bin/jaxrs-jersey1-petstore-server.sh +++ b/bin/jaxrs-jersey1-petstore-server.sh @@ -26,7 +26,7 @@ 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/JavaJaxRS -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey1 -DhideGenerationTimestamp=true,serverPort=8080 --library=jersey1 --artifact-id=swagger-jaxrs-jersey1-server" +ags="$@ generate -t modules/openapi-generator/src/main/resources/JavaJaxRS -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs-jersey -o samples/server/petstore/jaxrs/jersey1 -DhideGenerationTimestamp=true,serverPort=8080 --library=jersey1 --artifact-id=swagger-jaxrs-jersey1-server" echo "Removing files and folders under samples/server/petstore/jaxrs/jersey1/src/main" rm -rf samples/server/petstore/jaxrs/jersey1/src/main diff --git a/bin/jaxrs-jersey1-usetags-petstore-server.sh b/bin/jaxrs-jersey1-usetags-petstore-server.sh index c924bd496130..aef4d3cb9a40 100755 --- a/bin/jaxrs-jersey1-usetags-petstore-server.sh +++ b/bin/jaxrs-jersey1-usetags-petstore-server.sh @@ -26,7 +26,7 @@ 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/JavaJaxRS -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey1-useTags -DhideGenerationTimestamp=true,serverPort=8080 --library=jersey1 --artifact-id=swagger-jaxrs-jersey1-useTags --additional-properties useTags=true" +ags="$@ generate -t modules/openapi-generator/src/main/resources/JavaJaxRS -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs-jersey -o samples/server/petstore/jaxrs/jersey1-useTags -DhideGenerationTimestamp=true,serverPort=8080 --library=jersey1 --artifact-id=swagger-jaxrs-jersey1-useTags --additional-properties useTags=true" echo "Removing files and folders under samples/server/petstore/jaxrs/jersey1-useTags/src/main" rm -rf samples/server/petstore/jaxrs/jersey1-useTags/src/main diff --git a/bin/jaxrs-petstore-server-datelib-j8.sh b/bin/jaxrs-petstore-server-datelib-j8.sh index 450c50371500..85259949ad9a 100755 --- a/bin/jaxrs-petstore-server-datelib-j8.sh +++ b/bin/jaxrs-petstore-server-datelib-j8.sh @@ -26,6 +26,6 @@ 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/JavaJaxRS/ -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs -o samples/server/petstore/jaxrs-datelib-j8/ -c ./bin/jaxrs-datelib-j8.json -DhideGenerationTimestamp=true" +ags="$@ generate -t modules/openapi-generator/src/main/resources/JavaJaxRS/ -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs-jersey -o samples/server/petstore/jaxrs-datelib-j8/ -c ./bin/jaxrs-datelib-j8.json -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-petstore-server.sh b/bin/jaxrs-petstore-server.sh index da754611328b..78fa7a514c15 100755 --- a/bin/jaxrs-petstore-server.sh +++ b/bin/jaxrs-petstore-server.sh @@ -26,7 +26,7 @@ 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/JavaJaxRS -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey2 -DhideGenerationTimestamp=true,serverPort=8080" +ags="$@ generate -t modules/openapi-generator/src/main/resources/JavaJaxRS -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs-jersey -o samples/server/petstore/jaxrs/jersey2 -DhideGenerationTimestamp=true,serverPort=8080" echo "Removing files and folders under samples/server/petstore/jaxrs/jersey2/src/main" rm -rf samples/server/petstore/jaxrs/jersey2/src/main diff --git a/bin/jaxrs-usetags-petstore-server.sh b/bin/jaxrs-usetags-petstore-server.sh index e25075917592..c367e0d30e6c 100755 --- a/bin/jaxrs-usetags-petstore-server.sh +++ b/bin/jaxrs-usetags-petstore-server.sh @@ -26,7 +26,7 @@ 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/JavaJaxRS -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey2-useTags -DhideGenerationTimestamp=true,serverPort=8080 --artifact-id=swagger-jaxrs-jersey2-useTags --additional-properties useTags=true" +ags="$@ generate -t modules/openapi-generator/src/main/resources/JavaJaxRS -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs-jersey -o samples/server/petstore/jaxrs/jersey2-useTags -DhideGenerationTimestamp=true,serverPort=8080 --artifact-id=swagger-jaxrs-jersey2-useTags --additional-properties useTags=true" echo "Removing files and folders under samples/server/petstore/jaxrs/jersey2-useTags/src/main" rm -rf samples/server/petstore/jaxrs/jersey2-useTags/src/main diff --git a/bin/lua-petstore.sh b/bin/lua-petstore.sh index af41030a52d1..accd33d2df12 100755 --- a/bin/lua-petstore.sh +++ b/bin/lua-petstore.sh @@ -26,6 +26,6 @@ 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/lua -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l lua -o samples/client/petstore/lua -DpackageName=petstore" +ags="generate -t modules/openapi-generator/src/main/resources/lua -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l lua -o samples/client/petstore/lua -DpackageName=petstore $@" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/lumen-petstore-server.sh b/bin/lumen-petstore-server.sh index 9075f37eebfb..2adf14d722f7 100755 --- a/bin/lumen-petstore-server.sh +++ b/bin/lumen-petstore-server.sh @@ -26,6 +26,6 @@ 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/lumen -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l lumen -o samples/server/petstore/lumen" +ags="$@ generate -t modules/openapi-generator/src/main/resources/lumen -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l php-lumen -o samples/server/petstore/lumen" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/nancyfx-petstore-server-async.sh b/bin/nancyfx-petstore-server-async.sh index fd35d74309c8..6d7889d713f0 100755 --- a/bin/nancyfx-petstore-server-async.sh +++ b/bin/nancyfx-petstore-server-async.sh @@ -26,6 +26,6 @@ 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/nancyfx -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l nancyfx -o samples/server/petstore/nancyfx-async --additional-properties packageGuid={768B8DC6-54EE-4D40-9B20-7857E1D742A4},asyncServer=true" +ags="generate $@ -t modules/openapi-generator/src/main/resources/csharp-nancyfx -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l csharp-nancyfx -o samples/server/petstore/nancyfx-async --additional-properties packageGuid={768B8DC6-54EE-4D40-9B20-7857E1D742A4},asyncServer=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/nancyfx-petstore-server.sh b/bin/nancyfx-petstore-server.sh index ef6ebb42355a..5b10fba6bda4 100755 --- a/bin/nancyfx-petstore-server.sh +++ b/bin/nancyfx-petstore-server.sh @@ -26,6 +26,6 @@ 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/nancyfx -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l nancyfx -o samples/server/petstore/nancyfx --additional-properties packageGuid={768B8DC6-54EE-4D40-9B20-7857E1D742A4},asyncServer=false" +ags="generate $@ -t modules/openapi-generator/src/main/resources/csharp-nancyfx -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l csharp-nancyfx -o samples/server/petstore/nancyfx --additional-properties packageGuid={768B8DC6-54EE-4D40-9B20-7857E1D742A4},asyncServer=false" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/openapi3/flash-petstore.sh b/bin/openapi3/flash-petstore.sh new file mode 100755 index 000000000000..3e014317fd5c --- /dev/null +++ b/bin/openapi3/flash-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/openapi-generator/src/main/resources/flash -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -l flash -o samples/client/petstore/flash -c bin/flash-petstore.json" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/openapi3/lua-petstore.sh b/bin/openapi3/lua-petstore.sh new file mode 100755 index 000000000000..6b291e617f3a --- /dev/null +++ b/bin/openapi3/lua-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/openapi-generator/src/main/resources/lua -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -l lua -o samples/client/petstore/lua -DpackageName=petstore $@" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/openapi3/perl-petstore.sh b/bin/openapi3/perl-petstore.sh new file mode 100755 index 000000000000..3508fa2ae80a --- /dev/null +++ b/bin/openapi3/perl-petstore.sh @@ -0,0 +1,34 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +# complex module name used for testing +ags="$@ generate -i modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml -l perl -o samples/client/petstore/perl -DhideGenerationTimestamp=true" + +java $JAVA_OPTS -jar $executable $ags + +java $JAVA_OPTS -jar $executable $ags --additional-properties moduleName=Something::Deep -o samples/client/petstore/perl/deep_module_test diff --git a/bin/openapi3/php-petstore.sh b/bin/openapi3/php-petstore.sh new file mode 100755 index 000000000000..436b48d0e067 --- /dev/null +++ b/bin/openapi3/php-petstore.sh @@ -0,0 +1,37 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# cleanup tests +TEST_DIR="./samples/openapi3/client/petstore/php/SwaggerClient-php/test" +if [ -d $TEST_DIR ]; then + rm -rf $TEST_DIR +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/php -i modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml -l php -o samples/openapi3/client/petstore/php $@" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/openapi3/powershell-petstore.sh b/bin/openapi3/powershell-petstore.sh new file mode 100755 index 000000000000..823861528040 --- /dev/null +++ b/bin/openapi3/powershell-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/openapi-generator/src/main/resources/powershell -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -l powershell -o samples/client/petstore/powershell --additional-properties packageGuid=a27b908d-2a20-467f-bc32-af6f3a654ac5,csharpClientPath=\$ScriptDir\..\..\petstore\csharp\SwaggerClient $@" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/openapi3/qt5-petstore.sh b/bin/openapi3/qt5-petstore.sh new file mode 100755 index 000000000000..4c89d47c1ab4 --- /dev/null +++ b/bin/openapi3/qt5-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/openapi-generator/src/main/resources/qt5cpp -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -l cpp-qt5 -o samples/client/petstore/qt5cpp" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/openapi3/r-petstore.sh b/bin/openapi3/r-petstore.sh new file mode 100755 index 000000000000..1f4a03baa373 --- /dev/null +++ b/bin/openapi3/r-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/openapi-generator/src/main/resources/r -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -l r -o samples/client/petstore/r_test -DpackageName=petstore $@" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/openapi3/ruby-petstore.sh b/bin/openapi3/ruby-petstore.sh new file mode 100755 index 000000000000..56e0706e05f8 --- /dev/null +++ b/bin/openapi3/ruby-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/openapi-generator/src/main/resources/ruby -i modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml -l ruby -c bin/ruby-petstore.json -o samples/client/petstore/ruby $@" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/openapi3/security/php-petstore.sh b/bin/openapi3/security/php-petstore.sh new file mode 100755 index 000000000000..7c1a73680ff8 --- /dev/null +++ b/bin/openapi3/security/php-petstore.sh @@ -0,0 +1,37 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# cleanup tests +TEST_DIR="./samples/client/petstore-security-test/php/SwaggerClient-php/test" +if [ -d $TEST_DIR ]; then + rm -rf $TEST_DIR +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/php -i modules/openapi-generator/src/test/resources/3_0/petstore-security-test.yaml -l php -o samples/client/petstore-security-test/php" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/openapi3/sinatra-petstore-server.sh b/bin/openapi3/sinatra-petstore-server.sh new file mode 100755 index 000000000000..a755da596bb6 --- /dev/null +++ b/bin/openapi3/sinatra-petstore-server.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/openapi-generator/src/main/resources/sinatra -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -l ruby-sinatra -o samples/server/petstore/sinatra" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/pistache-server-petstore.sh b/bin/pistache-server-petstore.sh index 3a29261930aa..3abb4a4286b4 100755 --- a/bin/pistache-server-petstore.sh +++ b/bin/pistache-server-petstore.sh @@ -26,6 +26,6 @@ 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 -l pistache-server -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -o samples/server/petstore/pistache-server" +ags="$@ generate -l cpp-pistache-server -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -o samples/server/petstore/pistache-server" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/python-asyncio-petstore.sh b/bin/python-asyncio-petstore.sh index 95619d86e86f..9bfcc245810d 100755 --- a/bin/python-asyncio-petstore.sh +++ b/bin/python-asyncio-petstore.sh @@ -21,7 +21,7 @@ executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" if [ ! -f "$executable" ] then - mvn clean package + mvn clean package $@ fi # if you've executed sbt assembly previously it will use that instead. diff --git a/bin/python-flask-petstore.sh b/bin/python-flask-petstore.sh index 633ffc8991a4..7aea96fb2ed8 100755 --- a/bin/python-flask-petstore.sh +++ b/bin/python-flask-petstore.sh @@ -26,7 +26,7 @@ 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/flaskConnexion -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion -Dservice" +ags="generate -t modules/openapi-generator/src/main/resources/flaskConnexion -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion -Dservice $@" rm -rf samples/server/petstore/flaskConnexion/* java $JAVA_OPTS -jar $executable $ags diff --git a/bin/python-petstore.sh b/bin/python-petstore.sh index f0d5435c8d28..1a37b1b0c3b4 100755 --- a/bin/python-petstore.sh +++ b/bin/python-petstore.sh @@ -21,7 +21,7 @@ executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" if [ ! -f "$executable" ] then - mvn clean package + mvn clean package $@ fi # if you've executed sbt assembly previously it will use that instead. diff --git a/bin/python-tornado-petstore.sh b/bin/python-tornado-petstore.sh index b243413918f3..68126322f915 100755 --- a/bin/python-tornado-petstore.sh +++ b/bin/python-tornado-petstore.sh @@ -21,7 +21,7 @@ executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" if [ ! -f "$executable" ] then - mvn clean package + mvn clean package $@ fi # if you've executed sbt assembly previously it will use that instead. diff --git a/bin/qt5-petstore.sh b/bin/qt5-petstore.sh index 05454217bbf4..535c7ef0a050 100755 --- a/bin/qt5-petstore.sh +++ b/bin/qt5-petstore.sh @@ -26,6 +26,6 @@ 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/qt5cpp -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l qt5cpp -o samples/client/petstore/qt5cpp" +ags="$@ generate -t modules/openapi-generator/src/main/resources/qt5cpp -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l cpp-qt5 -o samples/client/petstore/qt5cpp" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/rails5-petstore-server.sh b/bin/rails5-petstore-server.sh index 6fc661cd6914..59d6a6cbc6e6 100755 --- a/bin/rails5-petstore-server.sh +++ b/bin/rails5-petstore-server.sh @@ -26,6 +26,6 @@ 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/rails5 -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l rails5 -o samples/server/petstore/rails5" +ags="$@ generate -t modules/openapi-generator/src/main/resources/rails5 -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l ruby-on-rails -o samples/server/petstore/rails5" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/restbed-petstore-server.sh b/bin/restbed-petstore-server.sh index 753db764da6a..0b15d89b3bde 100755 --- a/bin/restbed-petstore-server.sh +++ b/bin/restbed-petstore-server.sh @@ -26,6 +26,6 @@ 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 -l restbed -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -o samples/server/petstore/restbed" +ags="$@ generate -l cpp-restbed-server -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -o samples/server/petstore/restbed" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/run-all-petstore b/bin/run-all-petstore index 755ab2f749de..e9ca544b48a3 100755 --- a/bin/run-all-petstore +++ b/bin/run-all-petstore @@ -12,6 +12,7 @@ for SCRIPT in `ls -l ./bin/*.sh | grep -v all` do if [ -f $SCRIPT -a -x $SCRIPT ] then + echo "Running $SCRIPT" $SCRIPT rc=$? if [[ $rc != 0 ]] diff --git a/bin/security/typescript-inversify.sh b/bin/security/typescript-inversify.sh new file mode 100755 index 000000000000..0dcb407c41f9 --- /dev/null +++ b/bin/security/typescript-inversify.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/typescript-inversify -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l typescript-inversify -o samples/client/petstore-security-test/typescript-inversify" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/sinatra-petstore-server.sh b/bin/sinatra-petstore-server.sh index 936f083d1b90..9ea45cfed84e 100755 --- a/bin/sinatra-petstore-server.sh +++ b/bin/sinatra-petstore-server.sh @@ -26,6 +26,6 @@ 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/sinatra -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l sinatra -o samples/server/petstore/sinatra" +ags="$@ generate -t modules/openapi-generator/src/main/resources/sinatra -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l ruby-sinatra -o samples/server/petstore/sinatra" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/slim-petstore-server.sh b/bin/slim-petstore-server.sh index 4f6babedc65e..3e914956acd7 100755 --- a/bin/slim-petstore-server.sh +++ b/bin/slim-petstore-server.sh @@ -26,6 +26,6 @@ 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/slim -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l slim -o samples/server/petstore/slim" +ags="$@ generate -t modules/openapi-generator/src/main/resources/slim -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l php-slim -o samples/server/petstore/slim" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/springboot-petstore-server.sh b/bin/springboot-petstore-server.sh index 96d47814d4fa..982953550d6c 100755 --- a/bin/springboot-petstore-server.sh +++ b/bin/springboot-petstore-server.sh @@ -26,7 +26,7 @@ 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/JavaSpring -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l spring -o samples/server/petstore/springboot -DhideGenerationTimestamp=true" +ags="generate -t modules/openapi-generator/src/main/resources/JavaSpring -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l spring -o samples/server/petstore/springboot -DhideGenerationTimestamp=true $@" echo "Removing files and folders under samples/server/petstore/springboot/src/main" rm -rf samples/server/petstore/springboot/src/main diff --git a/bin/swift-petstore-all.sh b/bin/swift-petstore-all.sh index 1a1deaba0f47..de757c53a663 100755 --- a/bin/swift-petstore-all.sh +++ b/bin/swift-petstore-all.sh @@ -26,15 +26,15 @@ 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/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore.json -o samples/client/petstore/swift/default" +ags="$@ generate -t modules/openapi-generator/src/main/resources/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift2-deprecated -c ./bin/swift-petstore.json -o samples/client/petstore/swift/default" echo "#### Petstore Swift API client (default) ####" java $JAVA_OPTS -jar $executable $ags -ags="$@ generate -t modules/openapi-generator/src/main/resources/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit" +ags="$@ generate -t modules/openapi-generator/src/main/resources/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift2-deprecated -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit" echo "#### Petstore Swift API client (promisekit) ####" java $JAVA_OPTS -jar $executable $ags -ags="$@ generate -t modules/openapi-generator/src/main/resources/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-rxswift.json -o samples/client/petstore/swift/rxswift" +ags="$@ generate -t modules/openapi-generator/src/main/resources/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift2-deprecated -c ./bin/swift-petstore-rxswift.json -o samples/client/petstore/swift/rxswift" echo "#### Petstore Swift API client (rxswift) ####" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift-petstore-promisekit.sh b/bin/swift-petstore-promisekit.sh index 66033b7e724e..ef0daeed0bb8 100755 --- a/bin/swift-petstore-promisekit.sh +++ b/bin/swift-petstore-promisekit.sh @@ -26,6 +26,6 @@ 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/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit $@" +ags="generate -t modules/openapi-generator/src/main/resources/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift2-deprecated -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit $@" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift-petstore-rxswift.sh b/bin/swift-petstore-rxswift.sh index ba1ae40c70e3..a7dcc334c3be 100755 --- a/bin/swift-petstore-rxswift.sh +++ b/bin/swift-petstore-rxswift.sh @@ -26,6 +26,6 @@ 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/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-rxswift.json -o samples/client/petstore/swift/rxswift $@" +ags="generate -t modules/openapi-generator/src/main/resources/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift2-deprecated -c ./bin/swift-petstore-rxswift.json -o samples/client/petstore/swift/rxswift $@" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift-petstore.sh b/bin/swift-petstore.sh index 30a33f51a8b3..58f0458543af 100755 --- a/bin/swift-petstore.sh +++ b/bin/swift-petstore.sh @@ -26,6 +26,6 @@ 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/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore.json -o samples/client/petstore/swift/default $@" +ags="generate -t modules/openapi-generator/src/main/resources/swift -i modules/openapi-generator/src/test/resources/2_0/petstore.json -l swift2-deprecated -c ./bin/swift-petstore.json -o samples/client/petstore/swift/default $@" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift4-petstore.sh b/bin/swift4-petstore.sh index cf4930c6b12c..e1bfb6c6622c 100755 --- a/bin/swift4-petstore.sh +++ b/bin/swift4-petstore.sh @@ -26,6 +26,6 @@ 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/swift4 -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift4 -c ./bin/swift4-petstore.json -o samples/client/petstore/swift4/default" +ags="generate -t modules/openapi-generator/src/main/resources/swift4 -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift4 -c ./bin/swift4-petstore.json -o samples/client/petstore/swift4/default $@" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/tizen-petstore.sh b/bin/tizen-petstore.sh index 0143af8aba5a..eba4afa48403 100755 --- a/bin/tizen-petstore.sh +++ b/bin/tizen-petstore.sh @@ -26,6 +26,6 @@ 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/tizen -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l tizen -o samples/client/petstore/tizen" +ags="$@ generate -t modules/openapi-generator/src/main/resources/tizen -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l cpp-tizen -o samples/client/petstore/tizen" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-angular-v2-petstore.sh b/bin/typescript-angular-v2-petstore.sh index ac9a2004a4b2..250217a4b785 100755 --- a/bin/typescript-angular-v2-petstore.sh +++ b/bin/typescript-angular-v2-petstore.sh @@ -26,6 +26,6 @@ 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 -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l typescript-angular -o samples/client/petstore/typescript-angular-v2/default --additional-properties ngVersion=2" +ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l typescript-angular -o samples/client/petstore/typescript-angular-v2/default --additional-properties ngVersion=2 $@" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore-all.sh b/bin/typescript-fetch-petstore-all.sh index 6365b9032a6b..27cd5f104b0c 100755 --- a/bin/typescript-fetch-petstore-all.sh +++ b/bin/typescript-fetch-petstore-all.sh @@ -2,4 +2,5 @@ ./bin/typescript-fetch-petstore-target-es6.sh ./bin/typescript-fetch-petstore-with-npm-version.sh +./bin/typescript-fetch-petstore-interfaces.sh ./bin/typescript-fetch-petstore.sh diff --git a/bin/typescript-fetch-petstore-interfaces.sh b/bin/typescript-fetch-petstore-interfaces.sh new file mode 100755 index 000000000000..5d6e657a612d --- /dev/null +++ b/bin/typescript-fetch-petstore-interfaces.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l typescript-fetch -o samples/client/petstore/typescript-fetch/builds/with-interfaces -D withInterfaces=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-inversify-petstore.sh b/bin/typescript-inversify-petstore.sh new file mode 100755 index 000000000000..aa188a89e592 --- /dev/null +++ b/bin/typescript-inversify-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -l typescript-inversify -o samples/client/petstore/typescript-inversify" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/utils/detect_carriage_return.sh b/bin/utils/detect_carriage_return.sh index 2cef34af1009..d3281f584686 100755 --- a/bin/utils/detect_carriage_return.sh +++ b/bin/utils/detect_carriage_return.sh @@ -10,7 +10,7 @@ fi # grep for \r in the generators -grep -RUIl $'\r$' modules/openapi-generator/src/main/java/io/swagger/codegen/*.java +grep -RUIl $'\r$' modules/openapi-generator/src/main/java/org/openapitools/codegen/*.java if [ $? -ne 1 ]; then echo "Generators contain carriage return '/r'. Please remove it and try again." diff --git a/bin/utils/detect_merge_conflict.sh b/bin/utils/detect_merge_conflict.sh index b40d90d80fa2..d19c27cc565c 100755 --- a/bin/utils/detect_merge_conflict.sh +++ b/bin/utils/detect_merge_conflict.sh @@ -1,6 +1,6 @@ #!/bin/bash -# grep for '<<<<<<< HEAD' in swagger codegen +# grep for '<<<<<<< HEAD' in openapi generator grep -RUIl '<<<<<<< HEAD' modules/openapi-generator/src if [ $? -ne 1 ]; then diff --git a/bin/windows/cpprest-petstore.bat b/bin/windows/cpprest-petstore.bat index 3402c7ec7b3d..100c29a421ba 100755 --- a/bin/windows/cpprest-petstore.bat +++ b/bin/windows/cpprest-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -l cpprest -o samples\client\petstore\cpprest +set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -l cpp-restsdk -o samples\client\petstore\cpprest java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/jaxrs-cxf-petstore-server.bat b/bin/windows/jaxrs-cxf-petstore-server.bat new file mode 100644 index 000000000000..5355f7e456b9 --- /dev/null +++ b/bin/windows/jaxrs-cxf-petstore-server.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\JavaJaxRS\cxf -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs-cxf -o samples\server\petstore\jaxrs-cxf -DhideGenerationTimestamp=true + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/nancyfx-petstore-server.bat b/bin/windows/nancyfx-petstore-server.bat index 8419736382d6..25f2152acbda 100644 --- a/bin/windows/nancyfx-petstore-server.bat +++ b/bin/windows/nancyfx-petstore-server.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -l nancyfx -o samples\server\petstore\nancyfx\ +set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -l csharp-nancyfx -o samples\server\petstore\nancyfx\ java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/pistache-server-petstore.bat b/bin/windows/pistache-server-petstore.bat new file mode 100644 index 000000000000..216745f1a692 --- /dev/null +++ b/bin/windows/pistache-server-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -l cpp-pistache-server -o samples\server\petstore\pistache-server\ + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/qt5cpp-petstore.bat b/bin/windows/qt5cpp-petstore.bat index 21e2cb337539..103c825050f7 100755 --- a/bin/windows/qt5cpp-petstore.bat +++ b/bin/windows/qt5cpp-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -l qt5cpp -o samples\client\petstore\qt5cpp +set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -l cpp-qt5 -o samples\client\petstore\qt5cpp java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/restbed-petstore-server.bat b/bin/windows/restbed-petstore-server.bat index 864c6ae3f72c..8c0e53d4c4ec 100644 --- a/bin/windows/restbed-petstore-server.bat +++ b/bin/windows/restbed-petstore-server.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -l restbed -o samples\server\petstore\restbed\ +set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -l cpp-restbed-server -o samples\server\petstore\restbed\ java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-fetch-petstore-all.bat b/bin/windows/typescript-fetch-petstore-all.bat index ed41df84bb5c..69af38cf6a25 100644 --- a/bin/windows/typescript-fetch-petstore-all.bat +++ b/bin/windows/typescript-fetch-petstore-all.bat @@ -3,3 +3,4 @@ call bin\windows\typescript-fetch-petstore.bat call bin\windows\typescript-fetch-petstore-target-es6.bat call bin\windows\typescript-fetch-petstore-with-npm-version.bat +call bin\windows\typescript-fetch-petstore-interfaces.bat diff --git a/bin/windows/typescript-fetch-petstore-interfaces.bat b/bin/windows/typescript-fetch-petstore-interfaces.bat new file mode 100644 index 000000000000..c8d9179dafa0 --- /dev/null +++ b/bin/windows/typescript-fetch-petstore-interfaces.bat @@ -0,0 +1,12 @@ +@ECHO OFF + +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-fetch -o samples\client\petstore\typescript-fetch\builds\with-interfaces -D withInterfaces=true + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-inversify-petstore.bat b/bin/windows/typescript-inversify-petstore.bat new file mode 100644 index 000000000000..0e677041ecbb --- /dev/null +++ b/bin/windows/typescript-inversify-petstore.bat @@ -0,0 +1,14 @@ +@ECHO OFF + +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M + +echo +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-inversify -o samples\client\petstore\typescript-inversify\builds\default + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-inversify.bat b/bin/windows/typescript-inversify.bat new file mode 100755 index 000000000000..10ff5c02b6c5 --- /dev/null +++ b/bin/windows/typescript-inversify.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-inversify -o samples\client\petstore\typescript-inversify + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/ze-ph-petstore-server.sh b/bin/ze-ph-petstore-server.sh index 4f41a9d6bc14..5c6e694362ba 100755 --- a/bin/ze-ph-petstore-server.sh +++ b/bin/ze-ph-petstore-server.sh @@ -26,6 +26,6 @@ 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/ze-ph -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l ze-ph -o samples/server/petstore/ze-ph" +ags="$@ generate -t modules/openapi-generator/src/main/resources/ze-ph -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l php-ze-ph -o samples/server/petstore/ze-ph" java $JAVA_OPTS -jar $executable $ags diff --git a/circle.yml b/circle.yml index 6575be3c6f62..3d369706a288 100644 --- a/circle.yml +++ b/circle.yml @@ -15,6 +15,7 @@ dependencies: cache_directories: - "~/.m2" - "~/.sbt" + - "~/.iv2/cache" pre: - sudo add-apt-repository ppa:duggan/bats --yes diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index ca6b8d4e3614..902d5a0d07c5 100755 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -3,18 +3,18 @@ set -euo pipefail # GEN_DIR allows to share the entrypoint between Dockerfile and run-in-docker.sh (backward compatible) -GEN_DIR=${GEN_DIR:-/opt/swagger-codegen} +GEN_DIR=${GEN_DIR:-/opt/openapi-generator} JAVA_OPTS=${JAVA_OPTS:-"-Xmx1024M -DloggerPath=conf/log4j.properties"} -cli="${GEN_DIR}/modules/swagger-codegen-cli" -codegen="${cli}/target/swagger-codegen-cli.jar" -cmdsrc="${cli}/src/main/java/io/swagger/codegen/cmd" +cli="${GEN_DIR}/modules/openapi-generator-cli" +codegen="${cli}/target/openapi-generator-cli.jar" +cmdsrc="${cli}/src/main/java/org/openapitools/codegen/cmd" pattern="@Command(name = \"$1\"" if expr "x$1" : 'x[a-z][a-z-]*$' > /dev/null && fgrep -qe "$pattern" "$cmdsrc"/*.java || expr "$1" = 'help' > /dev/null; then # If ${GEN_DIR} has been mapped elsewhere from default, and that location has not been built if [[ ! -f "${codegen}" ]]; then - (cd "${GEN_DIR}" && exec mvn -am -pl "modules/swagger-codegen-cli" -Duser.home=$(dirname MAVEN_CONFIG) package) + (cd "${GEN_DIR}" && exec mvn -am -pl "modules/openapi-generator-cli" -Duser.home=$(dirname MAVEN_CONFIG) package) fi command=$1 shift diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Langs.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Langs.java index fcdd921dfa1a..fc657d2f480d 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Langs.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Langs.java @@ -11,12 +11,12 @@ /** * User: lanwen Date: 24.03.15 Time: 20:25 */ -@Command(name = "langs", description = "Shows available langs") +@Command(name = "langs", description = "Shows available languages (generators)") public class Langs implements Runnable { @Override public void run() { LambdaIterable langs = with(load(CodegenConfig.class)).extract(on(CodegenConfig.class).getName()); - System.out.printf("Available languages: %s%n", langs); + System.out.printf("Available languages (generators): %s%n", langs); } } diff --git a/modules/openapi-generator-cli/src/main/resources/version.properties b/modules/openapi-generator-cli/src/main/resources/version.properties new file mode 100644 index 000000000000..410af8cc6871 --- /dev/null +++ b/modules/openapi-generator-cli/src/main/resources/version.properties @@ -0,0 +1 @@ +version = ${project.version} diff --git a/modules/openapi-generator-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java b/modules/openapi-generator-cli/src/test/java/org/openapitools/codegen/cmd/GenerateTest.java similarity index 100% rename from modules/openapi-generator-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java rename to modules/openapi-generator-cli/src/test/java/org/openapitools/codegen/cmd/GenerateTest.java diff --git a/modules/openapi-generator-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java b/modules/openapi-generator-cli/src/test/java/org/openapitools/codegen/cmd/utils/OptionUtilsTest.java similarity index 100% rename from modules/openapi-generator-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java rename to modules/openapi-generator-cli/src/test/java/org/openapitools/codegen/cmd/utils/OptionUtilsTest.java diff --git a/modules/swagger-codegen-maven-plugin/README.md b/modules/openapi-generator-maven-plugin/README.md similarity index 84% rename from modules/swagger-codegen-maven-plugin/README.md rename to modules/openapi-generator-maven-plugin/README.md index a357057c7464..b28840b61503 100644 --- a/modules/swagger-codegen-maven-plugin/README.md +++ b/modules/openapi-generator-maven-plugin/README.md @@ -1,7 +1,7 @@ -swagger-codegen-maven-plugin +openapi-generator-maven-plugin ============================ -A Maven plugin to support the [swagger](http://swagger.io) code generation project +A Maven plugin to support the OpenAPI generator project Usage ============================ @@ -9,8 +9,8 @@ Usage Add to your `build->plugins` section (default phase is `generate-sources` phase) ```xml - io.swagger - swagger-codegen-maven-plugin + org.openapitools + openapi-generator-maven-plugin 2.3.1 @@ -18,7 +18,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase) generate - src/main/resources/api.yaml + ${project.basedir}/src/main/resources/api.yaml java src/gen/java/main @@ -49,7 +49,7 @@ mvn clean compile - `withXml` - enable XML annotations inside the generated models and API (only works with Java `language` and libraries that provide support for JSON and XML) - `configOptions` - a map of language-specific parameters (see below) - `configHelp` - dumps the configuration help for the specified library (generates no sources) -- `ignoreFileOverride` - specifies the full path to a `.swagger-codegen-ignore` used for pattern based overrides of generated outputs +- `ignoreFileOverride` - specifies the full path to a `.openapi-generator-ignore` used for pattern based overrides of generated outputs - `generateApis` - generate the apis (`true` by default) - `generateApiTests` - generate the api tests (`true` by default. Only available if `generateApis` is `true`) - `generateApiDocumentation` - generate the api documentation (`true` by default. Only available if `generateApis` is `true`) @@ -67,17 +67,17 @@ Specifying a custom generator is a bit different. It doesn't support the classpa ```xml - io.swagger - swagger-codegen-maven-plugin - ${swagger-codegen-maven-plugin-version} + org.openapitools + openapi-generator-maven-plugin + ${openapi-generator-maven-plugin-version} generate - src/main/resources/yaml/yamlfilename.yaml - + ${project.basedir}/src/main/resources/yaml/yamlfilename.yaml + com.my.package.for.GeneratorLanguage myTemplateDir diff --git a/modules/swagger-codegen-maven-plugin/examples/java-client.xml b/modules/openapi-generator-maven-plugin/examples/java-client.xml similarity index 95% rename from modules/swagger-codegen-maven-plugin/examples/java-client.xml rename to modules/openapi-generator-maven-plugin/examples/java-client.xml index 4ad322b060d8..d6827463e447 100644 --- a/modules/swagger-codegen-maven-plugin/examples/java-client.xml +++ b/modules/openapi-generator-maven-plugin/examples/java-client.xml @@ -1,6 +1,6 @@ 4.0.0 - io.swagger + org.openapitools sample-project jar 1.0-SNAPSHOT @@ -10,9 +10,9 @@ - io.swagger - swagger-codegen-maven-plugin - 2.2.2-SNAPSHOT + org.openapitools + openapi-generator-maven-plugin + 2.4.0-SNAPSHOT @@ -45,7 +45,7 @@ - io.swagger + org.openapitools swagger-annotations ${swagger-annotations-version} diff --git a/modules/swagger-codegen-maven-plugin/examples/swagger.yaml b/modules/openapi-generator-maven-plugin/examples/swagger.yaml similarity index 100% rename from modules/swagger-codegen-maven-plugin/examples/swagger.yaml rename to modules/openapi-generator-maven-plugin/examples/swagger.yaml diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/openapi-generator-maven-plugin/pom.xml similarity index 87% rename from modules/swagger-codegen-maven-plugin/pom.xml rename to modules/openapi-generator-maven-plugin/pom.xml index 28236f345ad4..d29b60618a7b 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/openapi-generator-maven-plugin/pom.xml @@ -2,15 +2,15 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - io.swagger - swagger-codegen-project - 2.4.0-SNAPSHOT + org.openapitools + openapi-generator-project + 3.0.0-SNAPSHOT ../.. - swagger-codegen-maven-plugin - swagger-codegen (maven-plugin) + openapi-generator-maven-plugin + openapi-generator (maven-plugin) maven-plugin - maven plugin to build modules from swagger codegen + maven plugin to build modules from openapi generator 3.2.5 @@ -45,8 +45,8 @@ 3.4 - io.swagger - swagger-codegen + org.openapitools + openapi-generator ${project.version} @@ -89,7 +89,7 @@ net.revelc.code formatter-maven-plugin - + ${project.basedir}${file.separator}${project.parent.relativePath}${file.separator}eclipse-formatter.xml diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java similarity index 91% rename from modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java rename to modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java index 446acc9849e0..07786d75c338 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.plugin; +package org.openapitools.codegen.plugin; /* * Copyright 2001-2005 The Apache Software Foundation. @@ -14,18 +14,18 @@ * the License. */ -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyAdditionalPropertiesKvp; -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyImportMappingsKvp; -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvp; -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsv; -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvp; -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvp; -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyAdditionalPropertiesKvpList; -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyImportMappingsKvpList; -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvpList; -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsvList; -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvpList; -import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvpList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyAdditionalPropertiesKvp; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyImportMappingsKvp; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvp; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsv; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvp; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvp; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyAdditionalPropertiesKvpList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyImportMappingsKvpList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvpList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsvList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvpList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvpList; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import java.io.File; @@ -40,15 +40,15 @@ import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; -import io.swagger.codegen.CliOption; -import io.swagger.codegen.ClientOptInput; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.DefaultGenerator; -import io.swagger.codegen.config.CodegenConfigurator; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.config.CodegenConfigurator; /** - * Goal which generates client/server code from a swagger json/yaml definition. + * Goal which generates client/server code from a OpenAPI json/yaml definition. */ @Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES) public class CodeGenMojo extends AbstractMojo { @@ -65,12 +65,12 @@ public class CodeGenMojo extends AbstractMojo { /** * Location of the output directory. */ - @Parameter(name = "output", property = "swagger.codegen.maven.plugin.output", - defaultValue = "${project.build.directory}/generated-sources/swagger") + @Parameter(name = "output", property = "openapi.generator.maven.plugin.output", + defaultValue = "${project.build.directory}/generated-sources/openapi") private File output; /** - * Location of the swagger spec, as URL or file. + * Location of the OpenAPI spec, as URL or file. */ @Parameter(name = "inputSpec", required = true) private String inputSpec; @@ -82,7 +82,7 @@ public class CodeGenMojo extends AbstractMojo { private String gitUserId; /** - * Git repo ID, e.g. swagger-codegen. + * Git repo ID, e.g. openapi-generator. */ @Parameter(name = "gitRepoId", required = false) private String gitRepoId; diff --git a/modules/swagger-generator/Dockerfile b/modules/openapi-generator-online/Dockerfile similarity index 100% rename from modules/swagger-generator/Dockerfile rename to modules/openapi-generator-online/Dockerfile diff --git a/modules/swagger-generator/pom.xml b/modules/openapi-generator-online/pom.xml similarity index 94% rename from modules/swagger-generator/pom.xml rename to modules/openapi-generator-online/pom.xml index bca8c7e48b8a..77ed6817b014 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/openapi-generator-online/pom.xml @@ -2,14 +2,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - io.swagger - swagger-codegen-project - 2.4.0-SNAPSHOT + org.openapitools + openapi-generator-project + 3.0.0-SNAPSHOT ../.. - swagger-generator + openapi-generator-online war - swagger-generator + openapi-generator-online src/main/java @@ -133,16 +133,16 @@ io.swagger swagger-jersey2-jaxrs - ${swagger-core-version} + 1.5.18 - io.swagger - swagger-codegen + org.openapitools + openapi-generator ${project.parent.version} - io.swagger - swagger-codegen + org.openapitools + openapi-generator ${project.parent.version} test-jar test diff --git a/modules/swagger-generator/sample.json b/modules/openapi-generator-online/sample.json similarity index 100% rename from modules/swagger-generator/sample.json rename to modules/openapi-generator-online/sample.json diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/Bootstrap.java similarity index 77% rename from modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/Bootstrap.java index a48a21355fc9..9f52e73096d9 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/Bootstrap.java @@ -12,7 +12,7 @@ * the License. */ -package io.swagger.generator; +package org.openapitools.codegen.online; import org.apache.commons.io.IOUtils; @@ -29,11 +29,11 @@ public class Bootstrap extends HttpServlet { public void init(ServletConfig config) throws ServletException { DynamicSwaggerConfig bc = new DynamicSwaggerConfig(); bc.setBasePath("/api"); - bc.setTitle("Swagger Generator"); - bc.setDescription("This is an online swagger codegen server. You can find out more " - + "at https://github.com/swagger-api/swagger-codegen or on [irc.freenode.net, #swagger](http://swagger.io/irc/)."); - bc.setTermsOfServiceUrl("http://swagger.io/terms/"); - bc.setContact("apiteam@swagger.io"); + bc.setTitle("OpenAPI Generator"); + bc.setDescription("This is an online OpenAPI generator. You can find out more " + + "at https://github.com/openapi-tools/openapi-generator"); + bc.setTermsOfServiceUrl("https://www.apache.org/licenses/LICENSE-2.0"); + bc.setContact("openapi-generator@gmail.com"); bc.setLicense("Apache 2.0"); InputStream stream = getClass().getResourceAsStream("/version.prop"); if (stream == null) { @@ -48,7 +48,7 @@ public void init(ServletConfig config) throws ServletException { } bc.setLicenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html"); - bc.setResourcePackage("io.swagger.generator.resource"); + bc.setResourcePackage("org.openapitools.codegen.online.resource"); bc.setScan(true); } } diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/DynamicSwaggerConfig.java similarity index 94% rename from modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/DynamicSwaggerConfig.java index 35d143d4b7e6..0aac6577a68e 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/DynamicSwaggerConfig.java @@ -1,8 +1,8 @@ -package io.swagger.generator; +package org.openapitools.codegen.online; -import io.swagger.codegen.Codegen; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenType; +import org.openapitools.codegen.Codegen; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenType; import io.swagger.jaxrs.config.BeanConfig; import io.swagger.models.Operation; import io.swagger.models.Path; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/exception/ApiException.java similarity index 94% rename from modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/exception/ApiException.java index ee5df08dade4..ff85b42a2d8f 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/exception/ApiException.java @@ -12,7 +12,7 @@ * the License. */ -package io.swagger.generator.exception; +package org.openapitools.codegen.online.exception; public class ApiException extends Exception { private static final long serialVersionUID = -5085112752305370687L; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/exception/BadRequestException.java similarity index 94% rename from modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/exception/BadRequestException.java index 6fa19c94c643..447128ebf1bd 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/exception/BadRequestException.java @@ -12,7 +12,7 @@ * the License. */ -package io.swagger.generator.exception; +package org.openapitools.codegen.online.exception; import org.apache.http.HttpStatus; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/exception/NotFoundException.java similarity index 94% rename from modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/exception/NotFoundException.java index f41d1402a48e..467fadec7095 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/exception/NotFoundException.java @@ -12,7 +12,7 @@ * the License. */ -package io.swagger.generator.exception; +package org.openapitools.codegen.online.exception; import org.apache.http.HttpStatus; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/http/Generator.java similarity index 91% rename from modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/http/Generator.java index 2435a3170ca1..8bb551f7129a 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/http/Generator.java @@ -1,12 +1,12 @@ -package io.swagger.generator.online; +package org.openapitools.codegen.online.http; import com.fasterxml.jackson.databind.JsonNode; -import io.swagger.codegen.*; -import io.swagger.generator.exception.ApiException; -import io.swagger.generator.exception.BadRequestException; -import io.swagger.generator.model.GeneratorInput; -import io.swagger.generator.model.InputOption; -import io.swagger.generator.util.ZipUtil; +import org.openapitools.codegen.*; +import org.openapitools.codegen.online.exception.ApiException; +import org.openapitools.codegen.online.exception.BadRequestException; +import org.openapitools.codegen.online.model.GeneratorInput; +import org.openapitools.codegen.online.model.InputOption; +import org.openapitools.codegen.online.util.ZipUtil; import io.swagger.models.Swagger; import io.swagger.models.auth.AuthorizationValue; import io.swagger.parser.SwaggerParser; @@ -86,7 +86,7 @@ private static String generate(String language, GeneratorInput opts, Type type) swagger = new SwaggerParser().read(opts.getSwaggerUrl()); } } else { - throw new BadRequestException("No swagger specification was supplied"); + throw new BadRequestException("No OpenAPI specification was supplied"); } } else if (opts.getAuthorizationValue() != null) { List authorizationValues = new ArrayList(); @@ -96,7 +96,7 @@ private static String generate(String language, GeneratorInput opts, Type type) swagger = new SwaggerParser().read(node, true); } if (swagger == null) { - throw new BadRequestException("The swagger specification supplied was not valid"); + throw new BadRequestException("The OpenAPI specification supplied was not valid"); } String destPath = null; @@ -113,7 +113,8 @@ private static String generate(String language, GeneratorInput opts, Type type) String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + destPath; String outputFilename = outputFolder + "-bundle.zip"; - clientOptInput.opts(clientOpts).swagger(swagger); + // TODO revise below + //clientOptInput.opts(clientOpts).swagger(swagger); CodegenConfig codegenConfig = null; try { diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/ApiResponse.java similarity index 97% rename from modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/ApiResponse.java index 28d4bdc0b1ae..b086eda99e76 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/ApiResponse.java @@ -12,7 +12,7 @@ * the License. */ -package io.swagger.generator.model; +package org.openapitools.codegen.online.model; import javax.xml.bind.annotation.XmlTransient; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/Generated.java similarity index 95% rename from modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/Generated.java index b1d68a5da17d..c806db5efcc6 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/Generated.java @@ -12,7 +12,7 @@ * the License. */ -package io.swagger.generator.model; +package org.openapitools.codegen.online.model; public class Generated { private String filename; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/GeneratorInput.java similarity index 96% rename from modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/GeneratorInput.java index 439c730c8bde..9f2699c0b490 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/GeneratorInput.java @@ -1,4 +1,4 @@ -package io.swagger.generator.model; +package org.openapitools.codegen.online.model; import com.fasterxml.jackson.databind.JsonNode; import io.swagger.annotations.ApiModelProperty; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/InputOption.java similarity index 97% rename from modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/InputOption.java index 371f21a9a8cd..1e072a5d30bb 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/InputOption.java @@ -12,7 +12,7 @@ * the License. */ -package io.swagger.generator.model; +package org.openapitools.codegen.online.model; public class InputOption { private String name; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/ResponseCode.java similarity index 94% rename from modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/ResponseCode.java index 37f20c9c04cf..f21d86233572 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/model/ResponseCode.java @@ -1,4 +1,4 @@ -package io.swagger.generator.model; +package org.openapitools.codegen.online.model; import io.swagger.annotations.ApiModelProperty; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/ExceptionWriter.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/resource/ExceptionWriter.java similarity index 83% rename from modules/swagger-generator/src/main/java/io/swagger/generator/resource/ExceptionWriter.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/resource/ExceptionWriter.java index e2fac57d7d07..eca58d7b50c0 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/ExceptionWriter.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/resource/ExceptionWriter.java @@ -1,10 +1,10 @@ -package io.swagger.generator.resource; +package org.openapitools.codegen.online.resource; -import io.swagger.generator.exception.ApiException; -import io.swagger.generator.exception.BadRequestException; -import io.swagger.generator.exception.NotFoundException; -import io.swagger.generator.model.ApiResponse; -import io.swagger.generator.util.ValidationException; +import org.openapitools.codegen.online.exception.ApiException; +import org.openapitools.codegen.online.exception.BadRequestException; +import org.openapitools.codegen.online.exception.NotFoundException; +import org.openapitools.codegen.online.model.ApiResponse; +import org.openapitools.codegen.online.util.ValidationException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/resource/SwaggerResource.java similarity index 94% rename from modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/resource/SwaggerResource.java index 4220e1034a63..0a977afa1602 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/resource/SwaggerResource.java @@ -1,17 +1,17 @@ -package io.swagger.generator.resource; +package org.openapitools.codegen.online.resource; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; -import io.swagger.codegen.CliOption; -import io.swagger.codegen.Codegen; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenType; -import io.swagger.generator.exception.BadRequestException; -import io.swagger.generator.model.Generated; -import io.swagger.generator.model.GeneratorInput; -import io.swagger.generator.model.ResponseCode; -import io.swagger.generator.online.Generator; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.Codegen; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.online.exception.BadRequestException; +import org.openapitools.codegen.online.model.Generated; +import org.openapitools.codegen.online.model.GeneratorInput; +import org.openapitools.codegen.online.model.ResponseCode; +import org.openapitools.codegen.online.http.Generator; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ApiOriginFilter.java similarity index 97% rename from modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ApiOriginFilter.java index b4eb8d92ff75..7939dcab4a35 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ApiOriginFilter.java @@ -12,7 +12,7 @@ * the License. */ -package io.swagger.generator.util; +package org.openapitools.codegen.online.util; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/JacksonJsonProvider.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/JacksonJsonProvider.java similarity index 91% rename from modules/swagger-generator/src/main/java/io/swagger/generator/util/JacksonJsonProvider.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/JacksonJsonProvider.java index c26f11aa6d2f..f40f968878a4 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/JacksonJsonProvider.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/JacksonJsonProvider.java @@ -1,4 +1,4 @@ -package io.swagger.generator.util; +package org.openapitools.codegen.online.util; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ValidationException.java similarity index 91% rename from modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ValidationException.java index 99eb397e9962..9de3c943b03e 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ValidationException.java @@ -1,4 +1,4 @@ -package io.swagger.generator.util; +package org.openapitools.codegen.online.util; public class ValidationException extends Exception { private static final long serialVersionUID = 6861195361018260380L; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationMessage.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ValidationMessage.java similarity index 91% rename from modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationMessage.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ValidationMessage.java index 40b265625010..fc447981ced3 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationMessage.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ValidationMessage.java @@ -1,4 +1,4 @@ -package io.swagger.generator.util; +package org.openapitools.codegen.online.util; public class ValidationMessage { private String path, message, severity; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ZipUtil.java similarity index 98% rename from modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java rename to modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ZipUtil.java index 80c1872b9993..06ca91f96c93 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/util/ZipUtil.java @@ -12,7 +12,7 @@ * the License. */ -package io.swagger.generator.util; +package org.openapitools.codegen.online.util; import java.io.BufferedInputStream; import java.io.File; diff --git a/modules/swagger-generator/src/main/resources/logback.xml b/modules/openapi-generator-online/src/main/resources/logback.xml similarity index 100% rename from modules/swagger-generator/src/main/resources/logback.xml rename to modules/openapi-generator-online/src/main/resources/logback.xml diff --git a/modules/swagger-generator/src/main/resources/version.prop b/modules/openapi-generator-online/src/main/resources/version.prop similarity index 100% rename from modules/swagger-generator/src/main/resources/version.prop rename to modules/openapi-generator-online/src/main/resources/version.prop diff --git a/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml b/modules/openapi-generator-online/src/main/webapp/WEB-INF/web.xml similarity index 87% rename from modules/swagger-generator/src/main/webapp/WEB-INF/web.xml rename to modules/openapi-generator-online/src/main/webapp/WEB-INF/web.xml index 904e0e34fb0b..190c07f4bd5f 100644 --- a/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml +++ b/modules/openapi-generator-online/src/main/webapp/WEB-INF/web.xml @@ -10,14 +10,14 @@ jersey.config.server.provider.packages io.swagger.jaxrs.json, - io.swagger.generator.resource + org.openapitools.codegen.online.resource jersey.config.server.provider.classnames io.swagger.online.ExceptionWriter, - io.swagger.generator.util.JacksonJsonProvider, + org.openapitools.codegen.online.util.JacksonJsonProvider, io.swagger.jaxrs.listing.ApiListingResource, io.swagger.jersey.listing.JerseyApiDeclarationProvider, io.swagger.jersey.listing.JerseyResourceListingProvider @@ -37,11 +37,11 @@ ApiOriginFilter - io.swagger.generator.util.ApiOriginFilter + org.openapitools.codegen.online.util.ApiOriginFilter Bootstrap - io.swagger.generator.Bootstrap + org.openapitools.codegen.online.Bootstrap generator.host localhost:8080 diff --git a/modules/swagger-generator/src/main/webapp/index.html b/modules/openapi-generator-online/src/main/webapp/index.html similarity index 100% rename from modules/swagger-generator/src/main/webapp/index.html rename to modules/openapi-generator-online/src/main/webapp/index.html diff --git a/modules/openapi-generator/pom.xml b/modules/openapi-generator/pom.xml index c37da7487703..c8b85086c3bf 100644 --- a/modules/openapi-generator/pom.xml +++ b/modules/openapi-generator/pom.xml @@ -198,20 +198,29 @@ - io.swagger - swagger-parser + io.swagger.core.v3 + swagger-models + ${swagger-core-version} + + + io.swagger.core.v3 + swagger-core + ${swagger-core-version} + + + io.swagger.parser.v3 + swagger-parser-core ${swagger-parser-version} - compile - io.swagger - swagger-compat-spec-parser + io.swagger.parser.v3 + swagger-parser-v3 ${swagger-parser-version} - io.swagger - swagger-core - ${swagger-core-version} + io.swagger.parser.v3 + swagger-parser + ${swagger-parser-version} com.samskivert diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CliOption.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CliOption.java index 0df2e8862e2e..1225ddb6e00c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CliOption.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CliOption.java @@ -1,10 +1,7 @@ package org.openapitools.codegen; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.StringProperty; - import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.v3.parser.util.SchemaTypeUtil; import java.util.LinkedHashMap; import java.util.Map; @@ -17,7 +14,7 @@ public class CliOption { private Map enumValues; public CliOption(String opt, String description) { - this(opt, description, StringProperty.TYPE); + this(opt, description, SchemaTypeUtil.STRING_TYPE); } public CliOption(String opt, String description, String type) { @@ -26,7 +23,6 @@ public CliOption(String opt, String description, String type) { this.type = type; } - @ApiModelProperty(name = "optionName") public String getOpt() { return opt; } @@ -39,7 +35,6 @@ public void setDescription(String description) { this.description = description; } - @ApiModelProperty(value = "Data type is based on the types supported by the JSON-Schema") public String getType() { return type; } @@ -80,11 +75,11 @@ public void setEnum(Map enumValues) { } public static CliOption newBoolean(String opt, String description) { - return new CliOption(opt, description, BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()); + return new CliOption(opt, description, SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()); } public static CliOption newString(String opt, String description) { - return new CliOption(opt, description, StringProperty.TYPE); + return new CliOption(opt, description, SchemaTypeUtil.STRING_TYPE); } @JsonIgnore diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/ClientOptInput.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/ClientOptInput.java index ddce1e60d1bb..74474c7740fa 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/ClientOptInput.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/ClientOptInput.java @@ -1,20 +1,18 @@ package org.openapitools.codegen; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.codegen.auth.AuthParser; -import io.swagger.models.Swagger; -import io.swagger.models.auth.AuthorizationValue; - +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.parser.core.models.AuthorizationValue; import java.util.List; +import org.openapitools.codegen.auth.AuthParser; public class ClientOptInput { private CodegenConfig config; private ClientOpts opts; - private Swagger swagger; + private OpenAPI openAPI; private List auths; - public ClientOptInput swagger(Swagger swagger) { - this.setSwagger(swagger); + public ClientOptInput openAPI(OpenAPI openAPI) { + this.setOpenAPI(openAPI); return this; } @@ -65,12 +63,11 @@ public void setOpts(ClientOpts opts) { this.opts = opts; } - @ApiModelProperty(dataType = "Object") - public Swagger getSwagger() { - return swagger; + public OpenAPI getOpenAPI() { + return openAPI; } - public void setSwagger(Swagger swagger) { - this.swagger = swagger; + public void setOpenAPI(OpenAPI openAPI) { + this.openAPI = openAPI; } -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/Codegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/Codegen.java index 5258365877d1..57cdc3fb268c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/Codegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/Codegen.java @@ -6,6 +6,8 @@ import java.util.Map; import java.util.ServiceLoader; +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.OpenAPI; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; @@ -16,8 +18,6 @@ import config.Config; import config.ConfigParser; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; /** * @deprecated use instead {@link org.openapitools.codegen.DefaultGenerator} @@ -51,7 +51,7 @@ public static void main(String[] args) { ClientOptInput clientOptInput = new ClientOptInput(); ClientOpts clientOpts = new ClientOpts(); - Swagger swagger = null; + OpenAPI openAPI = null; CommandLine cmd = null; try { @@ -89,7 +89,7 @@ public static void main(String[] args) { return; } if (cmd.hasOption("i")) { - swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true); + openAPI = new OpenAPIParser().readLocation(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), null).getOpenAPI(); } if (cmd.hasOption("c")) { String configFile = cmd.getOptionValue("c"); @@ -113,7 +113,7 @@ public static void main(String[] args) { try { clientOptInput .opts(clientOpts) - .swagger(swagger); + .openAPI(openAPI); new Codegen().opts(clientOptInput).generate(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java index cd861edfe1f1..41e0c27c15f0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java @@ -6,11 +6,10 @@ import com.samskivert.mustache.Mustache.Compiler; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.models.auth.SecuritySchemeDefinition; -import io.swagger.models.properties.Property; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.security.SecurityScheme; public interface CodegenConfig { CodegenType getTag(); @@ -65,7 +64,7 @@ public interface CodegenConfig { String escapeQuotationMark(String input); - String getTypeDeclaration(Property p); + String getTypeDeclaration(Schema schema); String getTypeDeclaration(String name); @@ -87,15 +86,15 @@ public interface CodegenConfig { void setOutputDir(String dir); - CodegenModel fromModel(String name, Model model); + CodegenModel fromModel(String name, Schema schema); - CodegenModel fromModel(String name, Model model, Map allDefinitions); + CodegenModel fromModel(String name, Schema schema, Map allDefinitions); - CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions, Swagger swagger); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions, OpenAPI openAPI); - CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions); - List fromSecurity(Map schemes); + List fromSecurity(Map schemas); Set defaultIncludes(); @@ -121,9 +120,9 @@ public interface CodegenConfig { Map reservedWordsMappings(); - void preprocessSwagger(Swagger swagger); + void preprocessOpenAPI(OpenAPI openAPI); - void processSwagger(Swagger swagger); + void processOpenAPI(OpenAPI openAPI); Compiler processCompiler(Compiler compiler); @@ -177,6 +176,10 @@ public interface CodegenConfig { void setRemoveOperationIdPrefix(boolean removeOperationIdPrefix); + public boolean isHideGenerationTimestamp(); + + public void setHideGenerationTimestamp(boolean hideGenerationTimestamp); + Map supportedLibraries(); void setLibrary(String library); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfigLoader.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfigLoader.java index 97505ec06875..a1cedc0dd7b7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfigLoader.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfigLoader.java @@ -28,7 +28,7 @@ public static CodegenConfig forName(String name) { try { return (CodegenConfig) Class.forName(name).newInstance(); } catch (Exception e) { - throw new RuntimeException("Can't load config class with name ".concat(name) + " Available: " + availableConfigs.toString(), e); + throw new RuntimeException("Can't load config class with name ".concat(name) + " Available:\n" + availableConfigs.toString(), e); } } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java index abe333dd3a5e..cf8a29642e32 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java @@ -102,6 +102,9 @@ public class CodegenConstants { public static final String SORT_PARAMS_BY_REQUIRED_FLAG = "sortParamsByRequiredFlag"; public static final String SORT_PARAMS_BY_REQUIRED_FLAG_DESC = "Sort method arguments to place required parameters before optional parameters."; + public static final String PREPEND_FORM_OR_BODY_PARAMETERS = "prependFormOrBodyParameters"; + public static final String PREPEND_FORM_OR_BODY_PARAMETERS_DESC = "Add form or body parameters to the beginning of the parameter list."; + public static final String USE_DATETIME_OFFSET = "useDateTimeOffset"; public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties"; 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 5e21ff6eecb7..56993a8fc5a7 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 @@ -1,14 +1,16 @@ package org.openapitools.codegen; +import io.swagger.v3.oas.models.ExternalDocumentation; +import io.swagger.v3.oas.models.media.Discriminator; + import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.Objects; -import io.swagger.models.ExternalDocs; - public class CodegenModel { public String parent, parentSchema; public List interfaces; @@ -21,7 +23,7 @@ public class CodegenModel { public String name, classname, title, description, classVarName, modelJson, dataType, xmlPrefix, xmlNamespace, xmlName; public String classFilename; // store the class file name, mainly used for import public String unescapedDescription; - public String discriminator; + public Discriminator discriminator; public String defaultValue; public String arrayModelType; public boolean isAlias; // Is this effectively an alias of another simple type @@ -41,9 +43,9 @@ public class CodegenModel { public Set imports = new TreeSet(); public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, hasOptional, isArrayModel, hasChildren; public boolean hasOnlyReadOnly = true; // true if all properties are read-only - public ExternalDocs externalDocs; + public ExternalDocumentation externalDocumentation; - public Map vendorExtensions; + public Map vendorExtensions = new HashMap(); //The type of the value from additional properties. Used in map like objects. public String additionalPropertiesType; @@ -131,7 +133,7 @@ public boolean equals(Object o) { return false; if (isEnum != that.isEnum) return false; - if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null) + if (externalDocumentation != null ? !externalDocumentation.equals(that.externalDocumentation) : that.externalDocumentation != null) return false; if (!Objects.equals(hasOnlyReadOnly, that.hasOnlyReadOnly)) return false; @@ -177,11 +179,303 @@ public int hashCode() { result = 31 * result + (hasMoreModels ? 13:31); result = 31 * result + (hasEnums ? 13:31); result = 31 * result + (isEnum ? 13:31); - result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0); + result = 31 * result + (externalDocumentation != null ? externalDocumentation.hashCode() : 0); result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0); result = 31 * result + Objects.hash(hasOnlyReadOnly); result = 31 * result + Objects.hash(hasChildren); result = 31 * result + Objects.hash(parentVars); return result; } + + public String getParent() { + return parent; + } + + public void setParent(String parent) { + this.parent = parent; + } + + public String getParentSchema() { + return parentSchema; + } + + public void setParentSchema(String parentSchema) { + this.parentSchema = parentSchema; + } + + public List getInterfaces() { + return interfaces; + } + + public void setInterfaces(List interfaces) { + this.interfaces = interfaces; + } + + public CodegenModel getParentModel() { + return parentModel; + } + + public void setParentModel(CodegenModel parentModel) { + this.parentModel = parentModel; + } + + public List getInterfaceModels() { + return interfaceModels; + } + + public void setInterfaceModels(List interfaceModels) { + this.interfaceModels = interfaceModels; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getClassname() { + return classname; + } + + public void setClassname(String classname) { + this.classname = classname; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getClassVarName() { + return classVarName; + } + + public void setClassVarName(String classVarName) { + this.classVarName = classVarName; + } + + public String getModelJson() { + return modelJson; + } + + public void setModelJson(String modelJson) { + this.modelJson = modelJson; + } + + public String getDataType() { + return dataType; + } + + public void setDataType(String dataType) { + this.dataType = dataType; + } + + public String getXmlPrefix() { + return xmlPrefix; + } + + public void setXmlPrefix(String xmlPrefix) { + this.xmlPrefix = xmlPrefix; + } + + public String getXmlNamespace() { + return xmlNamespace; + } + + public void setXmlNamespace(String xmlNamespace) { + this.xmlNamespace = xmlNamespace; + } + + public String getXmlName() { + return xmlName; + } + + public void setXmlName(String xmlName) { + this.xmlName = xmlName; + } + + public String getClassFilename() { + return classFilename; + } + + public void setClassFilename(String classFilename) { + this.classFilename = classFilename; + } + + public String getUnescapedDescription() { + return unescapedDescription; + } + + public void setUnescapedDescription(String unescapedDescription) { + this.unescapedDescription = unescapedDescription; + } + + public Discriminator getDiscriminator() { + return discriminator; + } + + public String getDiscriminatorName() { + return discriminator == null ? null : discriminator.getPropertyName(); + } + + public void setDiscriminator(Discriminator discriminator) { + this.discriminator = discriminator; + } + + public String getDefaultValue() { + return defaultValue; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public String getArrayModelType() { + return arrayModelType; + } + + public void setArrayModelType(String arrayModelType) { + this.arrayModelType = arrayModelType; + } + + public List getVars() { + return vars; + } + + public void setVars(List vars) { + this.vars = vars; + } + + public List getRequiredVars() { + return requiredVars; + } + + public void setRequiredVars(List requiredVars) { + this.requiredVars = requiredVars; + } + + public List getOptionalVars() { + return optionalVars; + } + + public void setOptionalVars(List optionalVars) { + this.optionalVars = optionalVars; + } + + public List getReadOnlyVars() { + return readOnlyVars; + } + + public void setReadOnlyVars(List readOnlyVars) { + this.readOnlyVars = readOnlyVars; + } + + public List getReadWriteVars() { + return readWriteVars; + } + + public void setReadWriteVars(List readWriteVars) { + this.readWriteVars = readWriteVars; + } + + public List getAllVars() { + return allVars; + } + + public void setAllVars(List allVars) { + this.allVars = allVars; + } + + public List getParentVars() { + return parentVars; + } + + public void setParentVars(List parentVars) { + this.parentVars = parentVars; + } + + public Map getAllowableValues() { + return allowableValues; + } + + public void setAllowableValues(Map allowableValues) { + this.allowableValues = allowableValues; + } + + public Set getMandatory() { + return mandatory; + } + + public void setMandatory(Set mandatory) { + this.mandatory = mandatory; + } + + public Set getAllMandatory() { + return allMandatory; + } + + public void setAllMandatory(Set allMandatory) { + this.allMandatory = allMandatory; + } + + public Set getImports() { + return imports; + } + + public void setImports(Set imports) { + this.imports = imports; + } + + public boolean isEmptyVars() { + return emptyVars; + } + + public void setEmptyVars(boolean emptyVars) { + this.emptyVars = emptyVars; + } + + public ExternalDocumentation getExternalDocumentation() { + return externalDocumentation; + } + + public void setExternalDocumentation(ExternalDocumentation externalDocumentation) { + this.externalDocumentation = externalDocumentation; + } + + public Map getVendorExtensions() { + return vendorExtensions; + } + + public void setVendorExtensions(Map vendorExtensions) { + this.vendorExtensions = vendorExtensions; + } + + public String getAdditionalPropertiesType() { + return additionalPropertiesType; + } + + public void setAdditionalPropertiesType(String additionalPropertiesType) { + this.additionalPropertiesType = additionalPropertiesType; + } } 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 3a733efb2337..e4511005bc6f 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 @@ -1,9 +1,12 @@ package org.openapitools.codegen; -import io.swagger.models.ExternalDocs; -import io.swagger.models.Tag; +import io.swagger.v3.oas.models.ExternalDocumentation; +import io.swagger.v3.oas.models.media.Discriminator; +import io.swagger.v3.oas.models.parameters.RequestBody; +import io.swagger.v3.oas.models.tags.Tag; import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -19,7 +22,8 @@ public class CodegenOperation { isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, isRestful, isDeprecated; public String path, operationId, returnType, httpMethod, returnBaseType, - returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse, discriminator; + returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse; + public Discriminator discriminator; public List> consumes, produces, prioritizedContentTypes; public CodegenParameter bodyParam; public List allParams = new ArrayList(); @@ -28,15 +32,17 @@ public class CodegenOperation { public List queryParams = new ArrayList(); public List headerParams = new ArrayList(); public List formParams = new ArrayList(); + public List cookieParams = new ArrayList(); public List requiredParams = new ArrayList(); + public List optionalParams = new ArrayList(); public List authMethods; public List tags; public List responses = new ArrayList(); public Set imports = new HashSet(); public List> examples; public List> requestBodyExamples; - public ExternalDocs externalDocs; - public Map vendorExtensions; + public ExternalDocumentation externalDocs; + public Map vendorExtensions = new HashMap(); public String nickname; // legacy support public String operationIdOriginal; // for plug-in public String operationIdLowerCase; // for markdown documentation @@ -97,6 +103,42 @@ public boolean getHasFormParams() { return nonempty(formParams); } + /** + * Check if there's at least one form parameter + * + * @return true if any cookie parameter exists, false otherwise + */ + public boolean getHasCookieParams() { + return nonempty(cookieParams); + } + + /** + * Check if there's at least one optional parameter + * + * @return true if any optional parameter exists, false otherwise + */ + public boolean getHasOptionalParams() { + return nonempty(optionalParams); + } + + /** + * Check if there's at least one required parameter + * + * @return true if any optional parameter exists, false otherwise + */ + public boolean getHasRequiredParams() { + return nonempty(requiredParams); + } + + /** + * Check if there's at least one response header + * + * @return true if header response exists, false otherwise + */ + public boolean getHasResponseHeaders() { + return nonempty(responseHeaders); + } + /** * Check if there's at least one example parameter * @@ -277,6 +319,12 @@ public boolean equals(Object o) { return false; if (formParams != null ? !formParams.equals(that.formParams) : that.formParams != null) return false; + if (cookieParams != null ? !cookieParams.equals(that.cookieParams) : that.cookieParams != null) + return false; + if (requiredParams != null ? !requiredParams.equals(that.requiredParams) : that.requiredParams!= null) + return false; + if (optionalParams != null ? !optionalParams.equals(that.optionalParams) : that.optionalParams!= null) + return false; if (authMethods != null ? !authMethods.equals(that.authMethods) : that.authMethods != null) return false; if (tags != null ? !tags.equals(that.tags) : that.tags != null) @@ -343,6 +391,9 @@ public int hashCode() { result = 31 * result + (queryParams != null ? queryParams.hashCode() : 0); result = 31 * result + (headerParams != null ? headerParams.hashCode() : 0); result = 31 * result + (formParams != null ? formParams.hashCode() : 0); + result = 31 * result + (cookieParams != null ? cookieParams.hashCode() : 0); + result = 31 * result + (requiredParams!= null ? requiredParams.hashCode() : 0); + result = 31 * result + (optionalParams != null ? optionalParams.hashCode() : 0); result = 31 * result + (authMethods != null ? authMethods.hashCode() : 0); result = 31 * result + (tags != null ? tags.hashCode() : 0); result = 31 * result + (responses != null ? responses.hashCode() : 0); @@ -357,4 +408,6 @@ public int hashCode() { result = 31 * result + (operationIdCamelCase != null ? operationIdCamelCase.hashCode() : 0); return result; } + + } 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 239ab40201c4..72d66b1c2094 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 @@ -16,12 +16,12 @@ public class CodegenParameter { public String jsonSchema; public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid; public boolean isListContainer, isMapContainer; - public boolean isFile, notFile; + public boolean isFile; public boolean isEnum; public List _enum; public Map allowableValues; public CodegenProperty items; - public Map vendorExtensions; + public Map vendorExtensions = new HashMap(); public boolean hasValidation; /** @@ -79,7 +79,6 @@ public class CodegenParameter { public CodegenParameter copy() { CodegenParameter output = new CodegenParameter(); output.isFile = this.isFile; - output.notFile = this.notFile; output.hasMore = this.hasMore; output.isContainer = this.isContainer; output.secondaryParam = this.secondaryParam; @@ -149,11 +148,6 @@ public CodegenParameter copy() { return output; } - @Override - public String toString() { - return String.format("%s(%s)", baseName, dataType); - } - @Override public boolean equals(Object o) { if (this == o) return true; @@ -242,8 +236,6 @@ public boolean equals(Object o) { return false; if (isFile != that.isFile) return false; - if (notFile != that.notFile) - return false; if (_enum != null ? !_enum.equals(that._enum) : that._enum != null) return false; if (allowableValues != null ? !allowableValues.equals(that.allowableValues) : that.allowableValues != null) @@ -322,7 +314,6 @@ public int hashCode() { result = 31 * result + (isListContainer ? 13:31); result = 31 * result + (isMapContainer ? 13:31); result = 31 * result + (isFile ? 13:31); - result = 31 * result + (notFile ? 13:31); result = 31 * result + (isEnum ? 1 : 0); result = 31 * result + (_enum != null ? _enum.hashCode() : 0); result = 31 * result + (allowableValues != null ? allowableValues.hashCode() : 0); @@ -343,5 +334,69 @@ public int hashCode() { result = 31 * result + (multipleOf != null ? multipleOf.hashCode() : 0); return result; } + + @java.lang.Override + public java.lang.String toString() { + return "CodegenParameter{" + + "isFormParam=" + isFormParam + + ", isQueryParam=" + isQueryParam + + ", isPathParam=" + isPathParam + + ", isHeaderParam=" + isHeaderParam + + ", isCookieParam=" + isCookieParam + + ", isBodyParam=" + isBodyParam + + ", hasMore=" + hasMore + + ", isContainer=" + isContainer + + ", secondaryParam=" + secondaryParam + + ", isCollectionFormatMulti=" + isCollectionFormatMulti + + ", isPrimitiveType=" + isPrimitiveType + + ", baseName='" + baseName + '\'' + + ", paramName='" + paramName + '\'' + + ", dataType='" + dataType + '\'' + + ", datatypeWithEnum='" + datatypeWithEnum + '\'' + + ", dataFormat='" + dataFormat + '\'' + + ", collectionFormat='" + collectionFormat + '\'' + + ", description='" + description + '\'' + + ", unescapedDescription='" + unescapedDescription + '\'' + + ", baseType='" + baseType + '\'' + + ", defaultValue='" + defaultValue + '\'' + + ", enumName='" + enumName + '\'' + + ", example='" + example + '\'' + + ", jsonSchema='" + jsonSchema + '\'' + + ", isString=" + isString + + ", isNumeric=" + isNumeric + + ", isInteger=" + isInteger + + ", isLong=" + isLong + + ", isNumber=" + isNumber + + ", isFloat=" + isFloat + + ", isDouble=" + isDouble + + ", isByteArray=" + isByteArray + + ", isBinary=" + isBinary + + ", isBoolean=" + isBoolean + + ", isDate=" + isDate + + ", isDateTime=" + isDateTime + + ", isUuid=" + isUuid + + ", isListContainer=" + isListContainer + + ", isMapContainer=" + isMapContainer + + ", isFile=" + isFile + + ", isEnum=" + isEnum + + ", _enum=" + _enum + + ", allowableValues=" + allowableValues + + ", items=" + items + + ", vendorExtensions=" + vendorExtensions + + ", hasValidation=" + hasValidation + + ", required=" + required + + ", maximum='" + maximum + '\'' + + ", exclusiveMaximum=" + exclusiveMaximum + + ", minimum='" + minimum + '\'' + + ", exclusiveMinimum=" + exclusiveMinimum + + ", maxLength=" + maxLength + + ", minLength=" + minLength + + ", pattern='" + pattern + '\'' + + ", maxItems=" + maxItems + + ", minItems=" + minItems + + ", uniqueItems=" + uniqueItems + + ", multipleOf=" + multipleOf + + '}'; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java index 0ab6cc82904e..35d863efb4a3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java @@ -46,7 +46,7 @@ public class CodegenProperty implements Cloneable { public List _enum; public Map allowableValues; public CodegenProperty items; - public Map vendorExtensions; + public Map vendorExtensions = new HashMap(); public boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template) public boolean isInherited; public String discriminatorValue; @@ -63,12 +63,317 @@ public class CodegenProperty implements Cloneable { public String xmlNamespace; public boolean isXmlWrapped = false; + public String getBaseName() { + return baseName; + } - @Override - public String toString() { - return String.format("%s(%s)", baseName, datatype); + public void setBaseName(String baseName) { + this.baseName = baseName; + } + + public String getComplexType() { + return complexType; + } + + public void setComplexType(String complexType) { + this.complexType = complexType; + } + + public String getGetter() { + return getter; + } + + public void setGetter(String getter) { + this.getter = getter; + } + + public String getSetter() { + return setter; + } + + public void setSetter(String setter) { + this.setter = setter; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDatatype() { + return datatype; + } + + public void setDatatype(String datatype) { + this.datatype = datatype; + } + + public String getDatatypeWithEnum() { + return datatypeWithEnum; + } + + public void setDatatypeWithEnum(String datatypeWithEnum) { + this.datatypeWithEnum = datatypeWithEnum; + } + + public String getDataFormat() { + return dataFormat; + } + + public void setDataFormat(String dataFormat) { + this.dataFormat = dataFormat; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMin() { + return min; + } + + public void setMin(String min) { + this.min = min; + } + + public String getMax() { + return max; + } + + public void setMax(String max) { + this.max = max; + } + + public String getDefaultValue() { + return defaultValue; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public String getDefaultValueWithParam() { + return defaultValueWithParam; + } + + public void setDefaultValueWithParam(String defaultValueWithParam) { + this.defaultValueWithParam = defaultValueWithParam; + } + + public String getBaseType() { + return baseType; + } + + public void setBaseType(String baseType) { + this.baseType = baseType; } + public String getContainerType() { + return containerType; + } + + public void setContainerType(String containerType) { + this.containerType = containerType; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getUnescapedDescription() { + return unescapedDescription; + } + + public void setUnescapedDescription(String unescapedDescription) { + this.unescapedDescription = unescapedDescription; + } + + public Integer getMaxLength() { + return maxLength; + } + + public void setMaxLength(Integer maxLength) { + this.maxLength = maxLength; + } + + public Integer getMinLength() { + return minLength; + } + + public void setMinLength(Integer minLength) { + this.minLength = minLength; + } + + public String getPattern() { + return pattern; + } + + public void setPattern(String pattern) { + this.pattern = pattern; + } + + public String getExample() { + return example; + } + + public void setExample(String example) { + this.example = example; + } + + public String getJsonSchema() { + return jsonSchema; + } + + public void setJsonSchema(String jsonSchema) { + this.jsonSchema = jsonSchema; + } + + public String getMinimum() { + return minimum; + } + + public void setMinimum(String minimum) { + this.minimum = minimum; + } + + public String getMaximum() { + return maximum; + } + + public void setMaximum(String maximum) { + this.maximum = maximum; + } + + public boolean getExclusiveMinimum() { + return exclusiveMinimum; + } + + public void setExclusiveMinimum(boolean exclusiveMinimum) { + this.exclusiveMinimum = exclusiveMinimum; + } + + public boolean getIExclusiveMaximum() { + return exclusiveMaximum; + } + + public void setExclusiveMaximum(boolean exclusiveMaximum) { + this.exclusiveMaximum = exclusiveMaximum; + } + + public boolean getRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } + + public boolean getSecondaryParam() { + return secondaryParam; + } + + public void setSecondaryParam(boolean secondaryParam) { + this.secondaryParam = secondaryParam; + } + + public List get_enum() { + return _enum; + } + + public void set_enum(List _enum) { + this._enum = _enum; + } + + public Map getAllowableValues() { + return allowableValues; + } + + public void setAllowableValues(Map allowableValues) { + this.allowableValues = allowableValues; + } + + public CodegenProperty getItems() { + return items; + } + + public void setItems(CodegenProperty items) { + this.items = items; + } + + public Map getVendorExtensions() { + return vendorExtensions; + } + + public void setVendorExtensions(Map vendorExtensions) { + this.vendorExtensions = vendorExtensions; + } + + public String getNameInCamelCase() { + return nameInCamelCase; + } + + public void setNameInCamelCase(String nameInCamelCase) { + this.nameInCamelCase = nameInCamelCase; + } + + public String getEnumName() { + return enumName; + } + + public void setEnumName(String enumName) { + this.enumName = enumName; + } + + public Integer getMaxItems() { + return maxItems; + } + + public void setMaxItems(Integer maxItems) { + this.maxItems = maxItems; + } + + public Integer getMinItems() { + return minItems; + } + + public void setMinItems(Integer minItems) { + this.minItems = minItems; + } + + public String getXmlPrefix() { + return xmlPrefix; + } + + public void setXmlPrefix(String xmlPrefix) { + this.xmlPrefix = xmlPrefix; + } + + public String getXmlName() { + return xmlName; + } + + public void setXmlName(String xmlName) { + this.xmlName = xmlName; + } + + public String getXmlNamespace() { + return xmlNamespace; + } + + public void setXmlNamespace(String xmlNamespace) { + this.xmlNamespace = xmlNamespace; + } @Override public int hashCode() @@ -369,5 +674,76 @@ public CodegenProperty clone() { } } - + @java.lang.Override + public java.lang.String toString() { + return "CodegenProperty{" + + "baseName='" + baseName + '\'' + + ", complexType='" + complexType + '\'' + + ", getter='" + getter + '\'' + + ", setter='" + setter + '\'' + + ", description='" + description + '\'' + + ", datatype='" + datatype + '\'' + + ", datatypeWithEnum='" + datatypeWithEnum + '\'' + + ", dataFormat='" + dataFormat + '\'' + + ", name='" + name + '\'' + + ", min='" + min + '\'' + + ", max='" + max + '\'' + + ", defaultValue='" + defaultValue + '\'' + + ", defaultValueWithParam='" + defaultValueWithParam + '\'' + + ", baseType='" + baseType + '\'' + + ", containerType='" + containerType + '\'' + + ", title='" + title + '\'' + + ", unescapedDescription='" + unescapedDescription + '\'' + + ", maxLength=" + maxLength + + ", minLength=" + minLength + + ", pattern='" + pattern + '\'' + + ", example='" + example + '\'' + + ", jsonSchema='" + jsonSchema + '\'' + + ", minimum='" + minimum + '\'' + + ", maximum='" + maximum + '\'' + + ", exclusiveMinimum=" + exclusiveMinimum + + ", exclusiveMaximum=" + exclusiveMaximum + + ", hasMore=" + hasMore + + ", required=" + required + + ", secondaryParam=" + secondaryParam + + ", hasMoreNonReadOnly=" + hasMoreNonReadOnly + + ", isPrimitiveType=" + isPrimitiveType + + ", isContainer=" + isContainer + + ", isNotContainer=" + isNotContainer + + ", isString=" + isString + + ", isNumeric=" + isNumeric + + ", isInteger=" + isInteger + + ", isLong=" + isLong + + ", isNumber=" + isNumber + + ", isFloat=" + isFloat + + ", isDouble=" + isDouble + + ", isByteArray=" + isByteArray + + ", isBinary=" + isBinary + + ", isFile=" + isFile + + ", isBoolean=" + isBoolean + + ", isDate=" + isDate + + ", isDateTime=" + isDateTime + + ", isUuid=" + isUuid + + ", isListContainer=" + isListContainer + + ", isMapContainer=" + isMapContainer + + ", isEnum=" + isEnum + + ", isReadOnly=" + isReadOnly + + ", _enum=" + _enum + + ", allowableValues=" + allowableValues + + ", items=" + items + + ", vendorExtensions=" + vendorExtensions + + ", hasValidation=" + hasValidation + + ", isInherited=" + isInherited + + ", discriminatorValue='" + discriminatorValue + '\'' + + ", nameInCamelCase='" + nameInCamelCase + '\'' + + ", enumName='" + enumName + '\'' + + ", maxItems=" + maxItems + + ", minItems=" + minItems + + ", isXmlAttribute=" + isXmlAttribute + + ", xmlPrefix='" + xmlPrefix + '\'' + + ", xmlName='" + xmlName + '\'' + + ", xmlNamespace='" + xmlNamespace + '\'' + + ", isXmlWrapped=" + isXmlWrapped + + '}'; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java index 99a61a4297a2..6087866d810b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java @@ -1,6 +1,7 @@ package org.openapitools.codegen; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -21,7 +22,7 @@ public class CodegenResponse { public boolean isFile = false; public Object schema; public String jsonSchema; - public Map vendorExtensions; + public Map vendorExtensions = new HashMap(); public boolean isWildcard() { return "0".equals(code) || "default".equals(code); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java index e87141f9ecb4..48c1c05bd79d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java @@ -1,5 +1,8 @@ package org.openapitools.codegen; +import io.swagger.v3.oas.models.security.Scopes; + +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -7,7 +10,7 @@ public class CodegenSecurity { public String name; public String type; public Boolean hasMore, isBasic, isOAuth, isApiKey; - public Map vendorExtensions; + public Map vendorExtensions = new HashMap(); // ApiKey specific public String keyParamName; public Boolean isKeyInQuery, isKeyInHeader; 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 299c9d51534e..70545c297841 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 @@ -3,66 +3,64 @@ import javax.annotation.Nullable; import java.io.File; import java.util.*; +import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.google.common.base.Function; +import com.google.common.collect.Lists; +import com.samskivert.mustache.Mustache.Compiler; + +import io.swagger.models.Model; +import io.swagger.v3.core.util.Json; +import io.swagger.v3.core.util.Yaml; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.headers.Header; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.BinarySchema; +import io.swagger.v3.oas.models.media.BooleanSchema; +import io.swagger.v3.oas.models.media.ByteArraySchema; +import io.swagger.v3.oas.models.media.ComposedSchema; +import io.swagger.v3.oas.models.media.DateSchema; +import io.swagger.v3.oas.models.media.DateTimeSchema; +import io.swagger.v3.oas.models.media.EmailSchema; +import io.swagger.v3.oas.models.media.FileSchema; +import io.swagger.v3.oas.models.media.IntegerSchema; +import io.swagger.v3.oas.models.media.MapSchema; +import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.media.NumberSchema; +import io.swagger.v3.oas.models.media.ObjectSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; +import io.swagger.v3.oas.models.media.UUIDSchema; +import io.swagger.v3.oas.models.parameters.CookieParameter; +import io.swagger.v3.oas.models.parameters.HeaderParameter; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.parameters.PathParameter; +import io.swagger.v3.oas.models.parameters.QueryParameter; +import io.swagger.v3.oas.models.parameters.RequestBody; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.responses.ApiResponses; +import io.swagger.v3.oas.models.security.OAuthFlow; +import io.swagger.v3.oas.models.security.OAuthFlows; +import io.swagger.v3.oas.models.security.SecurityScheme; +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.openapitools.codegen.examples.ExampleGenerator; +import org.openapitools.codegen.utils.ModelUtils; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Function; -import com.google.common.collect.Lists; -import com.samskivert.mustache.Mustache.Compiler; - -import org.openapitools.codegen.examples.ExampleGenerator; -import io.swagger.models.ArrayModel; -import io.swagger.models.ComposedModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Operation; -import io.swagger.models.RefModel; -import io.swagger.models.Response; -import io.swagger.models.Swagger; -import io.swagger.models.auth.ApiKeyAuthDefinition; -import io.swagger.models.auth.BasicAuthDefinition; -import io.swagger.models.auth.In; -import io.swagger.models.auth.OAuth2Definition; -import io.swagger.models.auth.SecuritySchemeDefinition; -import io.swagger.models.parameters.BodyParameter; -import io.swagger.models.parameters.CookieParameter; -import io.swagger.models.parameters.FormParameter; -import io.swagger.models.parameters.HeaderParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.parameters.PathParameter; -import io.swagger.models.parameters.QueryParameter; -import io.swagger.models.parameters.SerializableParameter; -import io.swagger.models.properties.AbstractNumericProperty; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BaseIntegerProperty; -import io.swagger.models.properties.BinaryProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.ByteArrayProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DecimalProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FileProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.PropertyBuilder; -import io.swagger.models.properties.PropertyBuilder.PropertyId; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; -import io.swagger.models.properties.UUIDProperty; -import io.swagger.util.Json; - -public class DefaultCodegen { +public class DefaultCodegen implements CodegenConfig { protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); protected String inputSpec; @@ -108,6 +106,7 @@ public class DefaultCodegen { protected Map specialCharReplacements = new HashMap(); // When a model is an alias for a simple type protected Map typeAliases = null; + protected Boolean prependFormOrBodyParameters = false; protected String ignoreFilePathOverride; @@ -128,11 +127,22 @@ public void processOpts() { this.setApiPackage((String) additionalProperties.get(CodegenConstants.API_PACKAGE)); } + if (additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + setHideGenerationTimestamp(convertPropertyToBooleanAndWriteBack(CodegenConstants.HIDE_GENERATION_TIMESTAMP)); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, hideGenerationTimestamp); + } + if (additionalProperties.containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { this.setSortParamsByRequiredFlag(Boolean.valueOf(additionalProperties .get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString())); } + if (additionalProperties.containsKey(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS)) { + this.setPrependFormOrBodyParameters(Boolean.valueOf(additionalProperties + .get(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS).toString())); + } + if (additionalProperties.containsKey(CodegenConstants.ENSURE_UNIQUE_PARAMS)) { this.setEnsureUniqueParams(Boolean.valueOf(additionalProperties .get(CodegenConstants.ENSURE_UNIQUE_PARAMS).toString())); @@ -143,11 +153,11 @@ public void processOpts() { .get(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS).toString())); } - if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)){ + if (additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)) { this.setModelNamePrefix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_PREFIX)); } - if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)){ + if (additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)) { this.setModelNameSuffix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX)); } @@ -158,7 +168,7 @@ public void processOpts() { } // override with any special post-processing for all models - @SuppressWarnings({ "static-method", "unchecked" }) + @SuppressWarnings({"static-method", "unchecked"}) public Map postProcessAllModels(Map objs) { if (supportsInheritance) { // Index all CodegenModels by model name. @@ -174,15 +184,15 @@ public Map postProcessAllModels(Map objs) { } // Fix up all parent and interface CodegenModel references. for (CodegenModel cm : allModels.values()) { - if (cm.parent != null) { - cm.parentModel = allModels.get(cm.parent); + if (cm.getParent() != null) { + cm.setParentModel(allModels.get(cm.getParent())); } - if (cm.interfaces != null && !cm.interfaces.isEmpty()) { - cm.interfaceModels = new ArrayList(cm.interfaces.size()); - for (String intf : cm.interfaces) { + if (cm.getInterfaces() != null && !cm.getInterfaces().isEmpty()) { + cm.setInterfaceModels(new ArrayList(cm.getInterfaces().size())); + for (String intf : cm.getInterfaces()) { CodegenModel intfModel = allModels.get(intf); if (intfModel != null) { - cm.interfaceModels.add(intfModel); + cm.getInterfaceModels().add(intfModel); } } } @@ -190,15 +200,15 @@ public Map postProcessAllModels(Map objs) { // Let parent know about all its children for (String name : allModels.keySet()) { CodegenModel cm = allModels.get(name); - CodegenModel parent = allModels.get(cm.parent); - // if a discriminator exists on the parent, don't add this child to the inheritance hierarchy + CodegenModel parent = allModels.get(cm.getParent()); + // if a discriminator exists on the parent, don't add this child to the inheritance heirarchy // TODO Determine what to do if the parent discriminator name == the grandparent discriminator name while (parent != null) { - if (parent.children == null) { - parent.children = new ArrayList(); + if (parent.getChildren() == null) { + parent.setChildren(new ArrayList()); } - parent.children.add(cm); - if (parent.discriminator == null) { + parent.getChildren().add(cm); + if (parent.getDiscriminator() == null) { parent = allModels.get(parent.parent); } else { parent = null; @@ -263,7 +273,7 @@ public Map postProcessModelsEnum(Map objs) { } /** - * Returns the common prefix of variables for enum naming if + * Returns the common prefix of variables for enum naming if * two or more variables are present * * @param vars List of variable names @@ -287,7 +297,7 @@ public String findCommonPrefixOfVars(List vars) { /** * Return the enum default value in the language specified format * - * @param value enum variable name + * @param value enum variable name * @param datatype data type * @return the default value for the enum */ @@ -299,7 +309,7 @@ public String toEnumDefaultValue(String value, String datatype) { * Return the enum value in the language specified format * e.g. status becomes "status" * - * @param value enum variable name + * @param value enum variable name * @param datatype data type * @return the sanitized value for enum */ @@ -314,7 +324,7 @@ public String toEnumValue(String value, String datatype) { /** * Return the sanitized variable name for enum * - * @param value enum variable name + * @param value enum variable name * @param datatype data type * @return the sanitized variable name for enum */ @@ -351,22 +361,22 @@ public Map postProcessSupportingFileData(Map obj // override to post-process any model properties @SuppressWarnings("unused") - public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { } // override to post-process any parameters @SuppressWarnings("unused") - public void postProcessParameter(CodegenParameter parameter){ + public void postProcessParameter(CodegenParameter parameter) { } //override with any special handling of the entire swagger spec @SuppressWarnings("unused") - public void preprocessSwagger(Swagger swagger) { + public void preprocessOpenAPI(OpenAPI openAPI) { } // override with any special handling of the entire swagger spec @SuppressWarnings("unused") - public void processSwagger(Swagger swagger) { + public void processOpenAPI(OpenAPI openAPI) { } // override with any special handling of the JMustache compiler @@ -391,7 +401,7 @@ public String escapeText(String input) { StringEscapeUtils.unescapeJava( StringEscapeUtils.escapeJava(input) .replace("\\/", "/")) - .replaceAll("[\\t\\n\\r]"," ") + .replaceAll("[\\t\\n\\r]", " ") .replace("\\", "\\\\") .replace("\"", "\\\"")); } @@ -399,6 +409,7 @@ public String escapeText(String input) { /** * override with any special text escaping logic to handle unsafe * characters so as to avoid code injection + * * @param input String to be cleaned up * @return string with unsafe characters removed or escaped */ @@ -414,6 +425,7 @@ public String escapeUnsafeCharacters(String input) { /** * Escape single and/or double quote to avoid code injection + * * @param input String to be cleaned up * @return string with quotation mark removed or escaped */ @@ -575,11 +587,11 @@ public void setModelPackage(String modelPackage) { this.modelPackage = modelPackage; } - public void setModelNamePrefix(String modelNamePrefix){ + public void setModelNamePrefix(String modelNamePrefix) { this.modelNamePrefix = modelNamePrefix; } - public void setModelNameSuffix(String modelNameSuffix){ + public void setModelNameSuffix(String modelNameSuffix) { this.modelNameSuffix = modelNameSuffix; } @@ -591,6 +603,10 @@ public void setSortParamsByRequiredFlag(Boolean sortParamsByRequiredFlag) { this.sortParamsByRequiredFlag = sortParamsByRequiredFlag; } + public void setPrependFormOrBodyParameters(Boolean prependFormOrBodyParameters) { + this.prependFormOrBodyParameters = prependFormOrBodyParameters; + } + public void setEnsureUniqueParams(Boolean ensureUniqueParams) { this.ensureUniqueParams = ensureUniqueParams; } @@ -741,7 +757,7 @@ public String toEnumName(CodegenProperty property) { * * @param name the name to be escaped * @return the escaped reserved word - * + *

* throws Runtime exception as reserved word is not allowed (default behavior) */ @SuppressWarnings("static-method") @@ -775,11 +791,9 @@ public String toApiImport(String name) { /** * Default constructor. - * This method will map between Swagger type and language-specified type, as well as mapping - * between Swagger type and the corresponding import statement for the language. This will + * This method will map between OAS type and language-specified type, as well as mapping + * between OAS type and the corresponding import statement for the language. This will * also add some language specified CLI options, if any. - * - * * returns string presentation of the example path (it's a constructor) */ public DefaultCodegen() { @@ -820,6 +834,7 @@ public DefaultCodegen() { typeMapping.put("binary", "byte[]"); typeMapping.put("file", "File"); typeMapping.put("UUID", "UUID"); + //typeMapping.put("BigDecimal", "BigDecimal"); //TODO need the mapping? instantiationTypes = new HashMap(); @@ -853,10 +868,12 @@ public DefaultCodegen() { CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants .ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); - // name formatting options cliOptions.add(CliOption.newBoolean(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, CodegenConstants .ALLOW_UNICODE_IDENTIFIERS_DESC).defaultValue(Boolean.FALSE.toString())); + // option to change the order of form/body parameter + cliOptions.add(CliOption.newBoolean(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, + CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS_DESC).defaultValue(Boolean.FALSE.toString())); // initialize special character mapping initalizeSpecialCharacterMapping(); @@ -917,8 +934,8 @@ protected String getSymbolName(String input) { /** * Return the example path * - * @param path the path of the operation - * @param operation Swagger operation object + * @param path the path of the operation + * @param operation OAS operation object * @return string presentation of the example path */ @SuppressWarnings("static-method") @@ -945,21 +962,28 @@ public String generateExamplePath(String path, Operation operation) { } paramPart.append(param.getName()).append("="); paramPart.append("{"); - if (qp.getCollectionFormat() != null) { + + // TODO support for multi, tsv? + if (qp.getStyle() != null) { paramPart.append(param.getName()).append("1"); - if ("csv".equals(qp.getCollectionFormat())) { - paramPart.append(","); - } else if ("pipes".equals(qp.getCollectionFormat())) { + if (Parameter.StyleEnum.FORM.equals(qp.getStyle())) { + if (qp.getExplode() != null && qp.getExplode()) { + paramPart.append(","); + } else { + paramPart.append("&").append(param.getName()).append("="); + paramPart.append(param.getName()).append("2"); + } + } else if (Parameter.StyleEnum.PIPEDELIMITED.equals(qp.getStyle())) { paramPart.append("|"); - } else if ("tsv".equals(qp.getCollectionFormat())) { - paramPart.append("\t"); - } else if ("multi".equals(qp.getCollectionFormat())) { - paramPart.append("&").append(param.getName()).append("="); - paramPart.append(param.getName()).append("2"); + } else if (Parameter.StyleEnum.SPACEDELIMITED.equals(qp.getStyle())) { + paramPart.append("%20"); + } else { + LOGGER.warn("query parameter '" + param.getName() + "style not support: " + qp.getStyle()); } } else { paramPart.append(param.getName()); } + paramPart.append("}"); if (!param.getRequired()) { paramPart.append("]"); @@ -975,23 +999,22 @@ public String generateExamplePath(String path, Operation operation) { /** * Return the instantiation type of the property, especially for map and array * - * @param p Swagger property object + * @param schema property schema * @return string presentation of the instantiation type of the property */ - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - Property additionalProperties2 = ap.getAdditionalProperties(); - String type = additionalProperties2.getType(); + public String toInstantiationType(Schema schema) { + if (ModelUtils.isMapSchema(schema)) { + Schema additionalProperties = (Schema) schema.getAdditionalProperties(); + String type = additionalProperties.getType(); if (null == type) { - LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" // - + "\tIn Property: " + p); + LOGGER.error("No Type defined for Additional Property " + additionalProperties + "\n" // + + "\tIn Property: " + schema); } - String inner = getSwaggerType(additionalProperties2); + String inner = getSchemaType(additionalProperties); return instantiationTypes.get("map") + ""; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); + } else if (ModelUtils.isArraySchema(schema)) { + ArraySchema arraySchema = (ArraySchema) schema; + String inner = getSchemaType(arraySchema.getItems()); return instantiationTypes.get("array") + "<" + inner + ">"; } else { return null; @@ -1001,7 +1024,7 @@ public String toInstantiationType(Property p) { /** * Return the example value of the parameter. * - * @param p Swagger property object + * @param p Codegen parameter */ public void setParameterExampleValue(CodegenParameter p) { @@ -1010,44 +1033,27 @@ public void setParameterExampleValue(CodegenParameter p) { /** * Return the example value of the property * - * @param p Swagger property object + * @param schema Property schema * @return string presentation of the example value of the property */ - public String toExampleValue(Property p) { - if(p.getExample() != null) { - return p.getExample().toString(); + public String toExampleValue(Schema schema) { + if (schema.getExample() != null) { + return schema.getExample().toString(); } - if (p instanceof StringProperty) { - return "null"; - } else if (p instanceof BooleanProperty) { + + if (ModelUtils.isBooleanSchema(schema)) { return "null"; - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(schema)) { return "null"; - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(schema)) { return "null"; - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getExample() != null) { - return dp.getExample().toString(); - } + } else if (ModelUtils.isNumberSchema(schema)) { return "null"; - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getExample() != null) { - return dp.getExample().toString(); - } + } else if (ModelUtils.isIntegerSchema(schema)) { return "null"; - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getExample() != null) { - return dp.getExample().toString(); - } + } else if (ModelUtils.isStringSchema(schema)) { return "null"; - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getExample() != null) { - return dp.getExample().toString(); - } + } else if (ModelUtils.isObjectSchema(schema)) { return "null"; } else { return "null"; @@ -1057,42 +1063,24 @@ public String toExampleValue(Property p) { /** * Return the default value of the property * - * @param p Swagger property object + * @param schema Property schema * @return string presentation of the default value of the property */ @SuppressWarnings("static-method") - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { + public String toDefaultValue(Schema schema) { + if (ModelUtils.isBooleanSchema(schema)) { return "null"; - } else if (p instanceof BooleanProperty) { + } else if (ModelUtils.isDateSchema(schema)) { return "null"; - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateTimeSchema(schema)) { return "null"; - } else if (p instanceof DateTimeProperty) { - return "null"; - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } + } else if (ModelUtils.isNumberSchema(schema)) { return "null"; - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } + } else if (ModelUtils.isIntegerSchema(schema)) { return "null"; - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } + } else if (ModelUtils.isStringSchema(schema)) { return "null"; - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } + } else if (ModelUtils.isObjectSchema(schema)) { return "null"; } else { return "null"; @@ -1103,70 +1091,90 @@ public String toDefaultValue(Property p) { * Return the property initialized from a data object * Useful for initialization with a plain object in Javascript * - * @param name Name of the property object - * @param p Swagger property object + * @param name Name of the property object + * @param schema Property schema * @return string presentation of the default value of the property */ @SuppressWarnings("static-method") - public String toDefaultValueWithParam(String name, Property p) { + public String toDefaultValueWithParam(String name, Schema schema) { return " = data." + name + ";"; } /** - * returns the swagger type for the property - * @param p Swagger property object + * returns the OpenAPI type for the property + * + * @param schema property schema * @return string presentation of the type **/ @SuppressWarnings("static-method") - public String getSwaggerType(Property p) { + public String getSchemaType(Schema schema) { + // datatype is the OAI type (e.g. integer, long, etc) String datatype = null; - if (p instanceof StringProperty && "number".equals(p.getFormat())) { - datatype = "BigDecimal"; - } else if ((p instanceof ByteArrayProperty) || (p instanceof StringProperty && "byte".equals(p.getFormat()))) { - datatype = "ByteArray"; - } else if (p instanceof BinaryProperty) { - datatype = "binary"; - } else if (p instanceof FileProperty) { - datatype = "file"; - } else if (p instanceof BooleanProperty) { - datatype = "boolean"; - } else if (p instanceof DateProperty) { - datatype = "date"; - } else if (p instanceof DateTimeProperty) { - datatype = "DateTime"; - } else if (p instanceof DoubleProperty) { - datatype = "double"; - } else if (p instanceof FloatProperty) { - datatype = "float"; - } else if (p instanceof IntegerProperty) { - datatype = "integer"; - } else if (p instanceof LongProperty) { - datatype = "long"; - } else if (p instanceof MapProperty) { - datatype = "map"; - } else if (p instanceof DecimalProperty) { - datatype = "number"; - } else if ( p instanceof UUIDProperty) { - datatype = "UUID"; - } else if (p instanceof RefProperty) { + + if (StringUtils.isNotBlank(schema.get$ref())) { // object try { - RefProperty r = (RefProperty) p; - datatype = r.get$ref(); - if (datatype.indexOf("#/definitions/") == 0) { + datatype = schema.get$ref(); + // get the model name from $ref + if (datatype.indexOf("#/components/schemas/") == 0) { + datatype = datatype.substring("#/components/schemas/".length()); + } else if (datatype.indexOf("#/definitions/") == 0) { datatype = datatype.substring("#/definitions/".length()); } } catch (Exception e) { - LOGGER.warn("Error obtaining the datatype from RefProperty:" + p + ". Datatype default to Object"); + LOGGER.warn("Error obtaining the datatype (" + datatype + ") from ref:" + schema + ". Datatype default to Object"); datatype = "Object"; - LOGGER.error(e.getMessage(), e); } - } else if (p instanceof StringProperty) { + return datatype; + } + + if (ModelUtils.isStringSchema(schema) && "number".equals(schema.getFormat())) { + // special handle of type: string, format: number + datatype = "BigDecimal"; + } else if (ModelUtils.isByteArraySchema(schema)) { + datatype = "ByteArray"; + } else if (ModelUtils.isFileSchema(schema)) { + datatype = "file"; + } else if (ModelUtils.isBinarySchema(schema)) { + datatype = SchemaTypeUtil.BINARY_FORMAT; + } else if (ModelUtils.isBooleanSchema(schema)) { + datatype = SchemaTypeUtil.BOOLEAN_TYPE; + } else if (ModelUtils.isDateSchema(schema)) { + datatype = SchemaTypeUtil.DATE_FORMAT; + } else if (ModelUtils.isDateTimeSchema(schema)) { + datatype = "DateTime"; + } else if (ModelUtils.isNumberSchema(schema)) { + if (schema.getFormat() == null) { // no format defined + datatype = "number"; + } else if (ModelUtils.isFloatSchema(schema)) { + datatype = SchemaTypeUtil.FLOAT_FORMAT; + } else if (ModelUtils.isDoubleSchema(schema)) { + datatype = SchemaTypeUtil.DOUBLE_FORMAT; + } else { + LOGGER.warn("Unknown `format` detected for " + schema.getName() + ": " + schema.getFormat()); + } + } else if (ModelUtils.isIntegerSchema(schema)) { + if (ModelUtils.isLongSchema(schema)) { + datatype = "long"; + } else { + datatype = schema.getType(); // integer + } + } else if (ModelUtils.isMapSchema(schema)) { + datatype = "map"; + } else if (ModelUtils.isUUIDSchema(schema)) { + datatype = "UUID"; + } else if (ModelUtils.isStringSchema(schema)) { datatype = "string"; } else { - if (p != null) { - datatype = p.getType(); + if (schema != null) { + // TODO the following check should be covered by ModelUtils.isMapSchema(schema) above so can be removed + if (SchemaTypeUtil.OBJECT_TYPE.equals(schema.getType()) && schema.getAdditionalProperties() != null) { + datatype = "map"; + } else { + datatype = schema.getType(); + } } } + return datatype; } @@ -1206,21 +1214,22 @@ public String getTypeDeclaration(String name) { /** * Output the type declaration of the property * - * @param p Swagger Property object + * @param schema property schema * @return a string presentation of the property type */ - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - if (typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); + public String getTypeDeclaration(Schema schema) { + String oasType = getSchemaType(schema); + if (typeMapping.containsKey(oasType)) { + return typeMapping.get(oasType); } - return swaggerType; + return oasType; } /** * Determine the type alias for the given type if it exists. This feature * is only used for Java, because the language does not have a aliasing * mechanism of its own. + * * @param name The type name. * @return The alias of the given type, if it exists. If there is no alias * for this type, then returns the input type name. @@ -1285,91 +1294,85 @@ public String toModelName(final String name) { } /** - * Convert Swagger Model object to Codegen Model object without providing all model definitions + * Convert OAS Model object to Codegen Model object without providing all model definitions * - * @param name the name of the model - * @param model Swagger Model object + * @param name the name of the model + * @param schema OAS Model object * @return Codegen Model object */ - public CodegenModel fromModel(String name, Model model) { - return fromModel(name, model, null); + public CodegenModel fromModel(String name, Schema schema) { + return fromModel(name, schema, null); } /** - * Convert Swagger Model object to Codegen Model object + * Convert OAS Model object to Codegen Model object * - * @param name the name of the model - * @param model Swagger Model object - * @param allDefinitions a map of all Swagger models from the spec + * @param name the name of the model + * @param schema OAS Model object + * @param allDefinitions a map of all OAS models from the spec * @return Codegen Model object */ - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema schema, Map allDefinitions) { if (typeAliases == null) { // Only do this once during first call typeAliases = getAllAliases(allDefinitions); } + CodegenModel m = CodegenModelFactory.newInstance(CodegenModelType.MODEL); + if (reservedWords.contains(name)) { m.name = escapeReservedWord(name); } else { m.name = name; } - m.title = escapeText(model.getTitle()); - m.description = escapeText(model.getDescription()); - m.unescapedDescription = model.getDescription(); + m.title = escapeText(schema.getTitle()); + m.description = escapeText(schema.getDescription()); + m.unescapedDescription = schema.getDescription(); m.classname = toModelName(name); m.classVarName = toVarName(name); m.classFilename = toModelFilename(name); - m.modelJson = Json.pretty(model); - m.externalDocs = model.getExternalDocs(); - m.vendorExtensions = model.getVendorExtensions(); + m.modelJson = Json.pretty(schema); + m.externalDocumentation = schema.getExternalDocs(); + if (schema.getExtensions() != null && !schema.getExtensions().isEmpty()) { + m.getVendorExtensions().putAll(schema.getExtensions()); + } m.isAlias = typeAliases.containsKey(name); + m.discriminator = schema.getDiscriminator(); - if (model instanceof ModelImpl) { - ModelImpl modelImpl = (ModelImpl) model; - m.discriminator = modelImpl.getDiscriminator(); - - if (modelImpl.getXml() != null) { - m.xmlPrefix = modelImpl.getXml().getPrefix(); - m.xmlNamespace = modelImpl.getXml().getNamespace(); - m.xmlName = modelImpl.getXml().getName(); - } + if (schema.getXml() != null) { + m.xmlPrefix = schema.getXml().getPrefix(); + m.xmlNamespace = schema.getXml().getNamespace(); + m.xmlName = schema.getXml().getName(); } - if (model instanceof ArrayModel) { - ArrayModel am = (ArrayModel) model; - ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); + if (ModelUtils.isArraySchema(schema)) { m.isArrayModel = true; - m.arrayModelType = fromProperty(name, arrayProperty).complexType; - addParentContainer(m, name, arrayProperty); - } else if (model instanceof RefModel) { - // TODO - } else if (model instanceof ComposedModel) { - final ComposedModel composed = (ComposedModel) model; - Map properties = new LinkedHashMap(); + m.arrayModelType = fromProperty(name, schema).complexType; + addParentContainer(m, name, schema); + } else if (schema instanceof ComposedSchema) { + final ComposedSchema composed = (ComposedSchema) schema; + Map properties = new LinkedHashMap(); List required = new ArrayList(); - Map allProperties; + Map allProperties; List allRequired; + if (supportsInheritance || supportsMixins) { - allProperties = new LinkedHashMap(); + allProperties = new LinkedHashMap(); allRequired = new ArrayList(); m.allVars = new ArrayList(); int modelImplCnt = 0; // only one inline object allowed in a ComposedModel - for (Model innerModel: ((ComposedModel)model).getAllOf()) { - if (innerModel instanceof ModelImpl) { - ModelImpl modelImpl = (ModelImpl) innerModel; - if (m.discriminator == null) { - m.discriminator = modelImpl.getDiscriminator(); - } - if (modelImpl.getXml() != null) { - m.xmlPrefix = modelImpl.getXml().getPrefix(); - m.xmlNamespace = modelImpl.getXml().getNamespace(); - m.xmlName = modelImpl.getXml().getName(); - } - if (modelImplCnt++ > 1) { - LOGGER.warn("More than one inline schema specified in allOf:. Only the first one is recognized. All others are ignored."); - break; // only one ModelImpl with discriminator allowed in allOf - } + for (Schema innerModel : composed.getAllOf()) { + if (m.discriminator == null) { + m.discriminator = schema.getDiscriminator(); + } + if (innerModel.getXml() != null) { + m.xmlPrefix = innerModel.getXml().getPrefix(); + m.xmlNamespace = innerModel.getXml().getNamespace(); + m.xmlName = innerModel.getXml().getName(); + } + if (modelImplCnt++ > 1) { + LOGGER.warn("More than one inline schema specified in allOf:. Only the first one is recognized. All others are ignored."); + break; // only one ModelImpl with discriminator allowed in allOf } } } else { @@ -1377,141 +1380,151 @@ public CodegenModel fromModel(String name, Model model, Map allDe allRequired = null; } // parent model - RefModel parent = (RefModel) composed.getParent(); + final String parentName = getParentName(composed, allDefinitions); + final Schema parent = StringUtils.isBlank(parentName) ? null : allDefinitions.get(parentName); + + List interfaces = getInterfaces(composed); // interfaces (intermediate models) - if (composed.getInterfaces() != null) { + if (interfaces != null) { if (m.interfaces == null) m.interfaces = new ArrayList(); - for (RefModel _interface : composed.getInterfaces()) { - Model interfaceModel = null; + + for (Schema interfaceSchema : interfaces) { + if (StringUtils.isBlank(interfaceSchema.get$ref())) { + continue; + } + Schema refSchema = null; + String ref = getSimpleRef(interfaceSchema.get$ref()); if (allDefinitions != null) { - interfaceModel = allDefinitions.get(_interface.getSimpleRef()); + refSchema = allDefinitions.get(ref); } - // set first interface with discriminator found as parent - if (parent == null - && ((interfaceModel instanceof ModelImpl && ((ModelImpl) interfaceModel).getDiscriminator() != null) - || (interfaceModel instanceof ComposedModel && isDiscriminatorInInterfaceTree((ComposedModel) interfaceModel, allDefinitions)))) { - parent = _interface; - } else { - final String interfaceRef = toModelName(_interface.getSimpleRef()); - m.interfaces.add(interfaceRef); - addImport(m, interfaceRef); - if (allDefinitions != null) { - if (!supportsMixins) { - addProperties(properties, required, interfaceModel, allDefinitions); - } - if (supportsInheritance) { - addProperties(allProperties, allRequired, interfaceModel, allDefinitions); - } + final String modelName = toModelName(ref); + m.interfaces.add(modelName); + addImport(m, modelName); + if (allDefinitions != null && refSchema != null) { + if (!supportsMixins && !supportsInheritance) { + addProperties(properties, required, refSchema, allDefinitions); + } + if (supportsInheritance) { + addProperties(allProperties, allRequired, refSchema, allDefinitions); } } } } if (parent != null) { - final String parentRef = parent.getSimpleRef(); - m.parentSchema = parentRef; - m.parent = toModelName(parent.getSimpleRef()); + m.parentSchema = parentName; + m.parent = toModelName(parentName); addImport(m, m.parent); - if (allDefinitions != null) { - final Model parentModel = allDefinitions.get(m.parentSchema); + if (allDefinitions != null && !allDefinitions.isEmpty()) { if (supportsInheritance) { - addProperties(allProperties, allRequired, parentModel, allDefinitions); + addProperties(allProperties, allRequired, parent, allDefinitions); } else { - addProperties(properties, required, parentModel, allDefinitions); + addProperties(properties, required, parent, allDefinitions); } } } // child model (properties owned by the model itself) - Model child = composed.getChild(); - if (child != null && child instanceof RefModel && allDefinitions != null) { - final String childRef = ((RefModel) child).getSimpleRef(); - child = allDefinitions.get(childRef); + Schema child = null; + if (composed.getAllOf() != null && !composed.getAllOf().isEmpty()) { + for (Schema component : composed.getAllOf()) { + if (component.get$ref() == null) { + child = component; + } + } } - if (child != null && child instanceof ModelImpl) { + if (child != null) { addProperties(properties, required, child, allDefinitions); if (supportsInheritance) { addProperties(allProperties, allRequired, child, allDefinitions); } } addVars(m, properties, required, allProperties, allRequired); + // TODO + //} else if (schema instanceof RefModel) { } else { - ModelImpl impl = (ModelImpl) model; - if (impl.getType() != null) { - Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null); - m.dataType = getSwaggerType(p); - } - if(impl.getEnum() != null && impl.getEnum().size() > 0) { + m.dataType = getSchemaType(schema); + if (schema.getEnum() != null && !schema.getEnum().isEmpty()) { m.isEnum = true; // comment out below as allowableValues is not set in post processing model enum m.allowableValues = new HashMap(); - m.allowableValues.put("values", impl.getEnum()); + m.allowableValues.put("values", schema.getEnum()); } - if (impl.getAdditionalProperties() != null) { - addAdditionPropertiesToCodeGenModel(m, impl); + if (ModelUtils.isMapSchema(schema)) { + addAdditionPropertiesToCodeGenModel(m, schema); } - addVars(m, impl.getProperties(), impl.getRequired()); + addVars(m, schema.getProperties(), schema.getRequired()); } if (m.vars != null) { - for(CodegenProperty prop : m.vars) { + for (CodegenProperty prop : m.vars) { postProcessModelProperty(m, prop); } } + LOGGER.debug("debugging fromModel return: " + m); + return m; } /** * Recursively look for a discriminator in the interface tree + * + * @param schema composed schema + * @param allDefinitions all schema defintion + * @return true if it's a discriminator */ - private boolean isDiscriminatorInInterfaceTree(ComposedModel model, Map allDefinitions) { - if (model == null || allDefinitions == null) + private boolean isDiscriminatorInInterfaceTree(ComposedSchema schema, Map allDefinitions) { + if (schema == null || allDefinitions == null || allDefinitions.isEmpty()) { return false; - - Model child = model.getChild(); - if (child instanceof ModelImpl && ((ModelImpl) child).getDiscriminator() != null) { + } + if (schema.getDiscriminator() != null) { return true; } - for (RefModel _interface : model.getInterfaces()) { - Model interfaceModel = allDefinitions.get(_interface.getSimpleRef()); - if (interfaceModel instanceof ModelImpl && ((ModelImpl) interfaceModel).getDiscriminator() != null) { + final List interfaces = getInterfaces(schema); + if (interfaces == null) { + return false; + } + for (Schema interfaceSchema : interfaces) { + if (interfaceSchema.getDiscriminator() != null) { return true; } - if (interfaceModel instanceof ComposedModel) { - - return isDiscriminatorInInterfaceTree((ComposedModel) interfaceModel, allDefinitions); + // TODO revise the logic below + if (interfaceSchema instanceof ComposedSchema) { + return isDiscriminatorInInterfaceTree((ComposedSchema) interfaceSchema, allDefinitions); } } return false; } - protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { - MapProperty mapProperty = new MapProperty(swaggerModel.getAdditionalProperties()); - addParentContainer(codegenModel, codegenModel.name, mapProperty); + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { + addParentContainer(codegenModel, codegenModel.name, schema); } - protected void addProperties(Map properties, - List required, Model model, - Map allDefinitions) { - - if (model instanceof ModelImpl) { - ModelImpl mi = (ModelImpl) model; - if (mi.getProperties() != null) { - properties.putAll(mi.getProperties()); - } - if (mi.getRequired() != null) { - required.addAll(mi.getRequired()); + protected void addProperties(Map properties, List required, Schema schema, Map allSchemas) { + if (schema instanceof ComposedSchema) { + ComposedSchema composedSchema = (ComposedSchema) schema; + if (composedSchema.getAllOf() == null) { + return; } - } else if (model instanceof RefModel) { - String interfaceRef = ((RefModel) model).getSimpleRef(); - Model interfaceModel = allDefinitions.get(interfaceRef); - addProperties(properties, required, interfaceModel, allDefinitions); - } else if (model instanceof ComposedModel) { - for (Model component :((ComposedModel) model).getAllOf()) { - addProperties(properties, required, component, allDefinitions); + + for (Schema component : composedSchema.getAllOf()) { + addProperties(properties, required, component, allSchemas); } + return; + } + + if (StringUtils.isNotBlank(schema.get$ref())) { + Schema interfaceSchema = allSchemas.get(getSimpleRef(schema.get$ref())); + addProperties(properties, required, interfaceSchema, allSchemas); + return; + } + if (schema.getProperties() != null) { + properties.putAll(schema.getProperties()); + } + if (schema.getRequired() != null) { + required.addAll(schema.getRequired()); } } @@ -1529,17 +1542,18 @@ public String getterAndSetterCapitalize(String name) { } /** - * Convert Swagger Property object to Codegen Property object + * Convert OAS Property object to Codegen Property object * * @param name name of the property - * @param p Swagger property object + * @param p OAS property object * @return Codegen Property object */ - public CodegenProperty fromProperty(String name, Property p) { + public CodegenProperty fromProperty(String name, Schema p) { if (p == null) { - LOGGER.error("unexpected missing property for name " + name); + LOGGER.error("Unexpected missing property for name " + name); return null; } + LOGGER.debug("debugging fromProperty for " + name + " : " + p); CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); property.name = toVarName(name); @@ -1551,7 +1565,7 @@ public CodegenProperty fromProperty(String name, Property p) { property.getter = toGetter(name); property.setter = toSetter(name); String example = toExampleValue(p); - if(!"null".equals(example)) { + if (!"null".equals(example)) { property.example = example; } property.defaultValue = toDefaultValue(p); @@ -1568,31 +1582,30 @@ public CodegenProperty fromProperty(String name, Property p) { property.xmlName = p.getXml().getName(); property.xmlNamespace = p.getXml().getNamespace(); } - property.vendorExtensions = p.getVendorExtensions(); + if (p.getExtensions() != null && !p.getExtensions().isEmpty()) { + property.getVendorExtensions().putAll(p.getExtensions()); + } - String type = getSwaggerType(p); - if (p instanceof AbstractNumericProperty) { - AbstractNumericProperty np = (AbstractNumericProperty) p; - if (np.getMinimum() != null) { - if (p instanceof BaseIntegerProperty) { // int, long - property.minimum = String.valueOf(np.getMinimum().longValue()); - } else { // double, decimal - property.minimum = String.valueOf(np.getMinimum()); - } - } - if (np.getMaximum() != null) { - if (p instanceof BaseIntegerProperty) { // int, long - property.maximum = String.valueOf(np.getMaximum().longValue()); - } else { // double, decimal - property.maximum = String.valueOf(np.getMaximum()); - } + String type = getSchemaType(p); + if (ModelUtils.isIntegerSchema(p)) { // integer type + property.isNumeric = Boolean.TRUE; + if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) { // int64/long format + property.isLong = Boolean.TRUE; + } else { // int32 format + property.isInteger = Boolean.TRUE; } - if (np.getExclusiveMinimum() != null) { - property.exclusiveMinimum = np.getExclusiveMinimum(); + if (p.getMinimum() != null) { + property.minimum = String.valueOf(p.getMinimum().longValue()); + } + if (p.getMaximum() != null) { + property.maximum = String.valueOf(p.getMaximum().longValue()); } - if (np.getExclusiveMaximum() != null) { - property.exclusiveMaximum = np.getExclusiveMaximum(); + if (p.getExclusiveMinimum() != null) { + property.exclusiveMinimum = p.getExclusiveMinimum(); + } + if (p.getExclusiveMaximum() != null) { + property.exclusiveMaximum = p.getExclusiveMaximum(); } // check if any validation rule defined @@ -1602,113 +1615,37 @@ public CodegenProperty fromProperty(String name, Property p) { // legacy support Map allowableValues = new HashMap(); - if (np.getMinimum() != null) { - allowableValues.put("min", np.getMinimum()); - } - if (np.getMaximum() != null) { - allowableValues.put("max", np.getMaximum()); + if (p.getMinimum() != null) { + allowableValues.put("min", p.getMinimum()); } - if(allowableValues.size() > 0) { - property.allowableValues = allowableValues; - } - } - - if (p instanceof StringProperty) { - StringProperty sp = (StringProperty) p; - property.maxLength = sp.getMaxLength(); - property.minLength = sp.getMinLength(); - property.pattern = toRegularExpression(sp.getPattern()); - - // check if any validation rule defined - if (property.pattern != null || property.minLength != null || property.maxLength != null) - property.hasValidation = true; - - property.isString = true; - if (sp.getEnum() != null) { - List _enum = sp.getEnum(); - property._enum = _enum; - property.isEnum = true; - - // legacy support - Map allowableValues = new HashMap(); - allowableValues.put("values", _enum); - property.allowableValues = allowableValues; + if (p.getMaximum() != null) { + allowableValues.put("max", p.getMaximum()); } - } - // type is integer and without format - if (p instanceof BaseIntegerProperty && !(p instanceof IntegerProperty) && !(p instanceof LongProperty)) { - BaseIntegerProperty sp = (BaseIntegerProperty) p; - property.isInteger = true; - property.isNumeric = true; - } - if (p instanceof IntegerProperty) { - IntegerProperty sp = (IntegerProperty) p; - property.isInteger = true; - if (sp.getEnum() != null) { - List _enum = sp.getEnum(); + if (p.getEnum() != null) { + List _enum = p.getEnum(); property._enum = new ArrayList(); - for(Integer i : _enum) { - property._enum.add(i.toString()); + for (Object i : _enum) { + property._enum.add(String.valueOf(i)); } property.isEnum = true; - - // legacy support - Map allowableValues = new HashMap(); allowableValues.put("values", _enum); - property.allowableValues = allowableValues; } - } - if (p instanceof LongProperty) { - LongProperty sp = (LongProperty) p; - property.isLong = true; - property.isNumeric = true; - if (sp.getEnum() != null) { - List _enum = sp.getEnum(); - property._enum = new ArrayList(); - for(Long i : _enum) { - property._enum.add(i.toString()); - } - property.isEnum = true; - // legacy support - Map allowableValues = new HashMap(); - allowableValues.put("values", _enum); + if (allowableValues.size() > 0) { property.allowableValues = allowableValues; } - } - if (p instanceof BooleanProperty) { + } else if (ModelUtils.isBooleanSchema(p)) { // boolean type property.isBoolean = true; property.getter = toBooleanGetter(name); - } - if (p instanceof BinaryProperty) { - property.isBinary = true; - } - if (p instanceof FileProperty) { - property.isFile = true; - } - if (p instanceof UUIDProperty) { - property.isString =true; - property.isUuid = true; - - } - if (p instanceof ByteArrayProperty) { - property.isByteArray = true; - } - // type is number and without format - if (p instanceof DecimalProperty && !(p instanceof DoubleProperty) && !(p instanceof FloatProperty)) { - DecimalProperty sp = (DecimalProperty) p; - property.isNumber = true; - } - if (p instanceof DoubleProperty) { - DoubleProperty sp = (DoubleProperty) p; - property.isDouble = true; - property.isNumeric = true; - if (sp.getEnum() != null) { - List _enum = sp.getEnum(); + } else if (ModelUtils.isDateSchema(p)) { // date format + property.isString = false; // for backward compatibility with 2.x + property.isDate = true; + if (p.getEnum() != null) { + List _enum = p.getEnum(); property._enum = new ArrayList(); - for(Double i : _enum) { - property._enum.add(i.toString()); + for (String i : _enum) { + property._enum.add(i); } property.isEnum = true; @@ -1717,16 +1654,14 @@ public CodegenProperty fromProperty(String name, Property p) { allowableValues.put("values", _enum); property.allowableValues = allowableValues; } - } - if (p instanceof FloatProperty) { - FloatProperty sp = (FloatProperty) p; - property.isFloat = true; - property.isNumeric = true; - if (sp.getEnum() != null) { - List _enum = sp.getEnum(); + } else if (ModelUtils.isDateTimeSchema(p)) { // date-time format + property.isString = false; // for backward compatibility with 2.x + property.isDateTime = true; + if (p.getEnum() != null) { + List _enum = p.getEnum(); property._enum = new ArrayList(); - for(Float i : _enum) { - property._enum.add(i.toString()); + for (String i : _enum) { + property._enum.add(i); } property.isEnum = true; @@ -1735,17 +1670,33 @@ public CodegenProperty fromProperty(String name, Property p) { allowableValues.put("values", _enum); property.allowableValues = allowableValues; } - } + } else if (ModelUtils.isStringSchema(p)) { + if (ModelUtils.isByteArraySchema(p)) { + property.isByteArray = true; + } else if (ModelUtils.isBinarySchema(p)) { + property.isBinary = true; + property.isFile = true; // file = binary in OAS3 + } else if (ModelUtils.isFileSchema(p)) { + property.isFile = true; + } else if (ModelUtils.isUUIDSchema(p)) { + // keep isString to true to make it backward compatible + property.isString = true; + property.isUuid = true; + } else { + property.isString = true; + } - if (p instanceof DateProperty) { - DateProperty sp = (DateProperty) p; - property.isDate = true; - if (sp.getEnum() != null) { - List _enum = sp.getEnum(); - property._enum = new ArrayList(); - for(String i : _enum) { - property._enum.add(i); - } + property.maxLength = p.getMaxLength(); + property.minLength = p.getMinLength(); + property.pattern = toRegularExpression(p.getPattern()); + + // check if any validation rule defined + if (property.pattern != null || property.minLength != null || property.maxLength != null) + property.hasValidation = true; + + if (p.getEnum() != null) { + List _enum = p.getEnum(); + property._enum = _enum; property.isEnum = true; // legacy support @@ -1753,15 +1704,39 @@ public CodegenProperty fromProperty(String name, Property p) { allowableValues.put("values", _enum); property.allowableValues = allowableValues; } - } - if (p instanceof DateTimeProperty) { - DateTimeProperty sp = (DateTimeProperty) p; - property.isDateTime = true; - if (sp.getEnum() != null) { - List _enum = sp.getEnum(); + } else if (ModelUtils.isNumberSchema(p)) { + property.isNumeric = Boolean.TRUE; + if (ModelUtils.isFloatSchema(p)) { // float + property.isFloat = Boolean.TRUE; + } else if (ModelUtils.isDoubleSchema(p)) { // double + property.isDouble = Boolean.TRUE; + } else { // type is number and without format + property.isNumber = Boolean.TRUE; + } + + if (p.getMinimum() != null) { + property.minimum = String.valueOf(p.getMinimum()); + } + if (p.getMaximum() != null) { + property.maximum = String.valueOf(p.getMaximum()); + } + if (p.getExclusiveMinimum() != null) { + property.exclusiveMinimum = p.getExclusiveMinimum(); + } + if (p.getExclusiveMaximum() != null) { + property.exclusiveMaximum = p.getExclusiveMaximum(); + } + + // check if any validation rule defined + // exclusive* are noop without corresponding min/max + if (property.minimum != null || property.maximum != null) + property.hasValidation = true; + + if (p.getEnum() != null && !p.getEnum().isEmpty()) { + List _enum = p.getEnum(); property._enum = new ArrayList(); - for(String i : _enum) { - property._enum.add(i); + for (Object i : _enum) { + property._enum.add(String.valueOf(i)); } property.isEnum = true; @@ -1771,8 +1746,10 @@ public CodegenProperty fromProperty(String name, Property p) { property.allowableValues = allowableValues; } } + property.datatype = getTypeDeclaration(p); property.dataFormat = p.getFormat(); + property.baseType = getSchemaType(p); // this can cause issues for clients which don't support enums if (property.isEnum) { @@ -1782,51 +1759,59 @@ public CodegenProperty fromProperty(String name, Property p) { property.datatypeWithEnum = property.datatype; } - property.baseType = getSwaggerType(p); - - if (p instanceof ArrayProperty) { + if (ModelUtils.isArraySchema(p)) { property.isContainer = true; property.isListContainer = true; property.containerType = "array"; - property.baseType = getSwaggerType(p); + property.baseType = getSchemaType(p); if (p.getXml() != null) { property.isXmlWrapped = p.getXml().getWrapped() == null ? false : p.getXml().getWrapped(); - property.xmlPrefix= p.getXml().getPrefix(); + property.xmlPrefix = p.getXml().getPrefix(); property.xmlNamespace = p.getXml().getNamespace(); property.xmlName = p.getXml().getName(); } + // handle inner property - ArrayProperty ap = (ArrayProperty) p; - property.maxItems = ap.getMaxItems(); - property.minItems = ap.getMinItems(); - String itemName = (String) p.getVendorExtensions().get("x-item-name"); + property.maxItems = p.getMaxItems(); + property.minItems = p.getMinItems(); + String itemName = null; + if (p.getExtensions() != null && p.getExtensions().get("x-item-name") != null) { + itemName = p.getExtensions().get("x-item-name").toString(); + } if (itemName == null) { itemName = property.name; } - CodegenProperty cp = fromProperty(itemName, ap.getItems()); + CodegenProperty cp = fromProperty(itemName, ((ArraySchema) p).getItems()); updatePropertyForArray(property, cp); - } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - + } else if (ModelUtils.isMapSchema(p)) { property.isContainer = true; property.isMapContainer = true; property.containerType = "map"; - property.baseType = getSwaggerType(p); - property.minItems = ap.getMinProperties(); - property.maxItems = ap.getMaxProperties(); + property.baseType = getSchemaType(p); + property.minItems = p.getMinProperties(); + property.maxItems = p.getMaxProperties(); // handle inner property - CodegenProperty cp = fromProperty("inner", ap.getAdditionalProperties()); + CodegenProperty cp = fromProperty("inner", (Schema) p.getAdditionalProperties()); updatePropertyForMap(property, cp); - } else { + } else { // model + // TODO revise the logic below + //if (StringUtils.isNotBlank(p.get$ref())) { + // property.baseType = getSimpleRef(p.get$ref()); + //} + // --END of revision + setNonArrayMapProperty(property, type); } + + LOGGER.debug("debugging from property return: " + property); return property; } /** * Update property for array(list) container - * @param property Codegen property + * + * @param property Codegen property * @param innerProperty Codegen inner property of map or list */ protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) { @@ -1857,7 +1842,8 @@ protected void updatePropertyForArray(CodegenProperty property, CodegenProperty /** * Update property for map container - * @param property Codegen property + * + * @param property Codegen property * @param innerProperty Codegen inner property of map or list */ protected void updatePropertyForMap(CodegenProperty property, CodegenProperty innerProperty) { @@ -1888,6 +1874,7 @@ protected void updatePropertyForMap(CodegenProperty property, CodegenProperty in /** * Update property for map container + * * @param property Codegen property * @return True if the inner most type is enum */ @@ -1914,6 +1901,7 @@ protected Map getInnerEnumAllowableValues(CodegenProperty proper /** * Update datatypeWithEnum for array container + * * @param property Codegen property */ protected void updateDataTypeWithEnumForArray(CodegenProperty property) { @@ -1941,6 +1929,7 @@ protected void updateDataTypeWithEnumForArray(CodegenProperty property) { /** * Update datatypeWithEnum for map container + * * @param property Codegen property */ protected void updateDataTypeWithEnumForMap(CodegenProperty property) { @@ -1976,11 +1965,11 @@ protected void setNonArrayMapProperty(CodegenProperty property, String type) { /** * Override with any special handling of response codes - * @param responses Swagger Operation's responses + * + * @param responses OAS Operation's responses * @return default method response or null if not found */ - protected Response findMethodResponse(Map responses) { - + protected ApiResponse findMethodResponse(ApiResponses responses) { String code = null; for (String responseCode : responses.keySet()) { if (responseCode.startsWith("2") || responseCode.equals("default")) { @@ -1996,36 +1985,42 @@ protected Response findMethodResponse(Map responses) { } /** - * Convert Swagger Operation object to Codegen Operation object (without providing a Swagger object) + * Convert OAS Operation object to Codegen Operation object (without providing a OAS object) * - * @param path the path of the operation + * @param path the path of the operation * @param httpMethod HTTP method - * @param operation Swagger operation object - * @param definitions a map of Swagger models + * @param operation OAS operation object + * @param schemas a map of OAS models * @return Codegen Operation object */ - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { - return fromOperation(path, httpMethod, operation, definitions, null); + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map schemas) { + return fromOperation(path, httpMethod, operation, schemas, null); } /** - * Convert Swagger Operation object to Codegen Operation object + * Convert OAS Operation object to Codegen Operation object * - * @param path the path of the operation + * @param path the path of the operation * @param httpMethod HTTP method - * @param operation Swagger operation object - * @param definitions a map of Swagger models - * @param swagger a Swagger object representing the spec + * @param operation OAS operation object + * @param schemas a map of OAS models + * @param openAPI a OAS object representing the spec * @return Codegen Operation object */ public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, - Map definitions, - Swagger swagger) { + Map schemas, + OpenAPI openAPI) { + LOGGER.debug("fromOperation => operation: " + operation); CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); Set imports = new HashSet(); - op.vendorExtensions = operation.getVendorExtensions(); + if (operation.getExtensions() != null && !operation.getExtensions().isEmpty()) { + op.vendorExtensions.putAll(operation.getExtensions()); + } + + if (operation == null) + throw new RuntimeException("operation cannnot be null in fromOperation"); // store the original operationId for plug-in op.operationIdOriginal = operation.getOperationId(); @@ -2035,7 +2030,7 @@ public CodegenOperation fromOperation(String path, if (removeOperationIdPrefix) { int offset = operationId.indexOf('_'); if (offset > -1) { - operationId = operationId.substring(offset+1); + operationId = operationId.substring(offset + 1); } } operationId = removeNonNameElementToCamelCase(operationId); @@ -2046,92 +2041,18 @@ public CodegenOperation fromOperation(String path, op.notes = escapeText(operation.getDescription()); op.hasConsumes = false; op.hasProduces = false; - if (operation.isDeprecated() != null) { - op.isDeprecated = operation.isDeprecated(); - } - - List consumes = new ArrayList(); - if (operation.getConsumes() != null) { - if (operation.getConsumes().size() > 0) { - // use consumes defined in the operation - consumes = operation.getConsumes(); - } else { - // empty list, do nothing to override global setting - } - } else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) { - // use consumes defined globally - consumes = swagger.getConsumes(); - LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); - } - - // if "consumes" is defined (per operation or using global definition) - if (consumes != null && consumes.size() > 0) { - List> c = new ArrayList>(); - int count = 0; - for (String key : consumes) { - Map mediaType = new HashMap(); - // escape quotation to avoid code injection - if ("*/*".equals(key)) { // "*/*" is a special case, do nothing - mediaType.put("mediaType", key); - } else { - mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); - } - count += 1; - if (count < consumes.size()) { - mediaType.put("hasMore", "true"); - } else { - mediaType.put("hasMore", null); - } - c.add(mediaType); - } - op.consumes = c; - op.hasConsumes = true; - } - - List produces = new ArrayList(); - if (operation.getProduces() != null) { - if (operation.getProduces().size() > 0) { - // use produces defined in the operation - produces = operation.getProduces(); - } else { - // empty list, do nothing to override global setting - } - } else if (swagger != null && swagger.getProduces() != null && swagger.getProduces().size() > 0) { - // use produces defined globally - produces = swagger.getProduces(); - LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId); + if (operation.getDeprecated() != null) { + op.isDeprecated = operation.getDeprecated(); } - // if "produces" is defined (per operation or using global definition) - if (produces != null && !produces.isEmpty()) { - List> c = new ArrayList>(); - int count = 0; - for (String key : produces) { - Map mediaType = new HashMap(); - // escape quotation to avoid code injection - if ("*/*".equals(key)) { // "*/*" is a special case, do nothing - mediaType.put("mediaType", key); - } else { - mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); - } - count += 1; - if (count < produces.size()) { - mediaType.put("hasMore", "true"); - } else { - mediaType.put("hasMore", null); - } - c.add(mediaType); - } - op.produces = c; - op.hasProduces = true; - } + addConsumesInfo(operation, op); if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { - Response methodResponse = findMethodResponse(operation.getResponses()); - - for (Map.Entry entry : operation.getResponses().entrySet()) { - Response response = entry.getValue(); - CodegenResponse r = fromResponse(entry.getKey(), response); + ApiResponse methodResponse = findMethodResponse(operation.getResponses()); + for (String key : operation.getResponses().keySet()) { + ApiResponse response = operation.getResponses().get(key); + addProducesInfo(response, op); + CodegenResponse r = fromResponse(key, response); r.hasMore = true; if (r.baseType != null && !defaultIncludes.contains(r.baseType) && @@ -2140,28 +2061,26 @@ public CodegenOperation fromOperation(String path, } r.isDefault = response == methodResponse; op.responses.add(r); - if (Boolean.TRUE.equals(r.isBinary) && Boolean.TRUE.equals(r.isDefault)){ + if (Boolean.TRUE.equals(r.isBinary) && Boolean.TRUE.equals(r.isDefault)) { op.isResponseBinary = Boolean.TRUE; } - if (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.isDefault)){ + if (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.isDefault)) { op.isResponseFile = Boolean.TRUE; } } op.responses.get(op.responses.size() - 1).hasMore = false; if (methodResponse != null) { - if (methodResponse.getSchema() != null) { - CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); - - Property responseProperty = methodResponse.getSchema(); + final Schema responseSchema = getSchemaFromResponse(methodResponse); + if (responseSchema != null) { + CodegenProperty cm = fromProperty("response", responseSchema); - if (responseProperty instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) responseProperty; - CodegenProperty innerProperty = fromProperty("response", ap.getItems()); + if (ModelUtils.isArraySchema(responseSchema)) { + ArraySchema as = (ArraySchema) responseSchema; + CodegenProperty innerProperty = fromProperty("response", as.getItems()); op.returnBaseType = innerProperty.baseType; - } else if (responseProperty instanceof MapProperty) { - MapProperty ap = (MapProperty) responseProperty; - CodegenProperty innerProperty = fromProperty("response", ap.getAdditionalProperties()); + } else if (ModelUtils.isMapSchema(responseSchema)) { + CodegenProperty innerProperty = fromProperty("response", (Schema) responseSchema.getAdditionalProperties()); op.returnBaseType = innerProperty.baseType; } else { if (cm.complexType != null) { @@ -2170,16 +2089,36 @@ public CodegenOperation fromOperation(String path, op.returnBaseType = cm.baseType; } } - op.examples = new ExampleGenerator(definitions).generate(methodResponse.getExamples(), operation.getProduces(), responseProperty); - op.defaultResponse = toDefaultValue(responseProperty); + + // generate examples + if (ModelUtils.isArraySchema(responseSchema)) { // array of schema + ArraySchema as = (ArraySchema) responseSchema; + if (as.getItems() != null && StringUtils.isEmpty(as.getItems().get$ref())) { // arary of primtive types + op.examples = new ExampleGenerator(schemas).generate((Map) responseSchema.getExample(), + new ArrayList(getProducesInfo(operation)), as.getItems(), openAPI); + } else if (as.getItems() != null && !StringUtils.isEmpty(as.getItems().get$ref())) { // array of model + op.examples = new ExampleGenerator(schemas).generate((Map) responseSchema.getExample(), + new ArrayList(getProducesInfo(operation)), getSimpleRef(as.getItems().get$ref()), openAPI); + } else { + // TODO log warning message as such case is not handled at the moment + } + } else if (StringUtils.isEmpty(responseSchema.get$ref())) { // primtiive type (e.g. integer, string) + op.examples = new ExampleGenerator(schemas).generate((Map) responseSchema.getExample(), + new ArrayList(getProducesInfo(operation)), responseSchema, openAPI); + } else { // model + op.examples = new ExampleGenerator(schemas).generate((Map) responseSchema.getExample(), + new ArrayList(getProducesInfo(operation)), getSimpleRef(responseSchema.get$ref()), openAPI); + } + + op.defaultResponse = toDefaultValue(responseSchema); op.returnType = cm.datatype; - op.hasReference = definitions != null && definitions.containsKey(op.returnBaseType); + op.hasReference = schemas != null && schemas.containsKey(op.returnBaseType); // lookup discriminator - if (definitions != null) { - Model m = definitions.get(op.returnBaseType); - if (m != null) { - CodegenModel cmod = fromModel(op.returnBaseType, m, definitions); + if (schemas != null) { + Schema schema = schemas.get(op.returnBaseType); + if (schema != null) { + CodegenModel cmod = fromModel(op.returnBaseType, schema, schemas); op.discriminator = cmod.discriminator; } } @@ -2205,7 +2144,6 @@ public CodegenOperation fromOperation(String path, } List parameters = operation.getParameters(); - CodegenParameter bodyParam = null; List allParams = new ArrayList(); List bodyParams = new ArrayList(); List pathParams = new ArrayList(); @@ -2214,58 +2152,100 @@ public CodegenOperation fromOperation(String path, List cookieParams = new ArrayList(); List formParams = new ArrayList(); List requiredParams = new ArrayList(); + List optionalParams = new ArrayList(); - if (parameters != null) { - for (Parameter param : parameters) { - CodegenParameter p = fromParameter(param, imports); - // rename parameters to make sure all of them have unique names - if (ensureUniqueParams) { - while (true) { - boolean exists = false; - for (CodegenParameter cp : allParams) { - if (p.paramName.equals(cp.paramName)) { - exists = true; - break; - } - } - if (exists) { - p.paramName = generateNextName(p.paramName); - } else { - break; - } + CodegenParameter bodyParam = null; + RequestBody requestBody = operation.getRequestBody(); + if (requestBody != null) { + if ("application/x-www-form-urlencoded".equalsIgnoreCase(getContentType(requestBody)) || + "multipart/form-data".equalsIgnoreCase(getContentType(requestBody))) { + // process form parameters + formParams = fromRequestBodyToFormParameters(requestBody, schemas, imports); + // add form parameters to the beginning of all parameter list + if (prependFormOrBodyParameters) { + for (CodegenParameter cp : formParams) { + allParams.add(cp.copy()); } } + } else { + // process body parameter + if (StringUtils.isNotBlank(requestBody.get$ref())) { + requestBody = openAPI.getComponents().getRequestBodies().get(getSimpleRef(requestBody.get$ref())); + } + bodyParam = fromRequestBody(requestBody, schemas, imports); + bodyParam.description = requestBody.getDescription(); + bodyParams.add(bodyParam); - allParams.add(p); - // Issue #2561 (neilotoole) : Moved setting of isParam flags - // from here to fromParameter(). - if (param instanceof QueryParameter) { - queryParams.add(p.copy()); - } else if (param instanceof PathParameter) { - pathParams.add(p.copy()); - } else if (param instanceof HeaderParameter) { - headerParams.add(p.copy()); - } else if (param instanceof CookieParameter) { - cookieParams.add(p.copy()); - } else if (param instanceof BodyParameter) { - bodyParam = p; - bodyParams.add(p.copy()); - if(definitions != null) { - op.requestBodyExamples = new ExampleGenerator(definitions).generate(null, operation.getConsumes(), bodyParam.dataType); - } - } else if (param instanceof FormParameter) { - formParams.add(p.copy()); + if (prependFormOrBodyParameters) { + allParams.add(bodyParam); } - if (p.required) { //required parameters - requiredParams.add(p.copy()); - } else { // optional parameters - op.hasOptionalParams = true; + // add example + if (schemas != null) { + op.requestBodyExamples = new ExampleGenerator(schemas).generate(null, new ArrayList(getConsumesInfo(operation)), bodyParam.baseType, openAPI); } } } - for (String i : imports) { + if (parameters != null) { + for (Parameter param : parameters) { + if (StringUtils.isNotBlank(param.get$ref())) { + param = getParameterFromRef(param.get$ref(), openAPI); + } + + CodegenParameter p = fromParameter(param, imports); + + allParams.add(p); + + if (param instanceof QueryParameter || "query".equalsIgnoreCase(param.getIn())) { + queryParams.add(p.copy()); + } else if (param instanceof PathParameter || "path".equalsIgnoreCase(param.getIn())) { + pathParams.add(p.copy()); + } else if (param instanceof HeaderParameter || "header".equalsIgnoreCase(param.getIn())) { + headerParams.add(p.copy()); + } else if (param instanceof CookieParameter || "cookie".equalsIgnoreCase(param.getIn())) { + cookieParams.add(p.copy()); + } else { + LOGGER.warn("Unknown parameter type " + p.baseType + " for " + p.baseName); + } + + } + } + + // add form/body parameter (if any) to the end of all parameter list + if (!prependFormOrBodyParameters) { + for (CodegenParameter cp : formParams) { + allParams.add(cp.copy()); + } + + for (CodegenParameter cp : bodyParams) { + allParams.add(cp.copy()); + } + } + + // ensure unique parameter name + for (CodegenParameter cp : allParams) { + if (ensureUniqueParams) { + if (isParameterNameUnique(cp, allParams)) { + continue; + } else { + cp.paramName = generateNextName(cp.paramName); + } + } + } + + // create optional, required parameters + for (CodegenParameter cp : allParams) { + if (cp.required) { //required parameters + requiredParams.add(cp.copy()); + } else { // optional parameters + optionalParams.add(cp.copy()); + op.hasOptionalParams = true; + } + } + + // add imports to operation import tag + for (String i : imports) { if (needToImport(i)) { op.imports.add(i); } @@ -2291,9 +2271,10 @@ public int compare(CodegenParameter one, CodegenParameter another) { op.pathParams = addHasMore(pathParams); op.queryParams = addHasMore(queryParams); op.headerParams = addHasMore(headerParams); - // op.cookieParams = cookieParams; + op.cookieParams = addHasMore(cookieParams); op.formParams = addHasMore(formParams); op.requiredParams = addHasMore(requiredParams); + op.optionalParams = addHasMore(optionalParams); op.externalDocs = operation.getExternalDocs(); // legacy support op.nickname = op.operationId; @@ -2314,273 +2295,303 @@ public int compare(CodegenParameter one, CodegenParameter another) { return op; } + public boolean isParameterNameUnique(CodegenParameter p, List parameters) { + for (CodegenParameter parameter : parameters) { + if (System.identityHashCode(p) == System.identityHashCode(parameter)) { + continue; // skip itself + } + + if (p.paramName.equals(parameter.paramName)) { + return false; + } + } + + return true; + } + /** - * Convert Swagger Response object to Codegen Response object + * Convert OAS Response object to Codegen Response object * * @param responseCode HTTP response code - * @param response Swagger Response object + * @param response OAS Response object * @return Codegen Response object */ - public CodegenResponse fromResponse(String responseCode, Response response) { + public CodegenResponse fromResponse(String responseCode, ApiResponse response) { CodegenResponse r = CodegenModelFactory.newInstance(CodegenModelType.RESPONSE); if ("default".equals(responseCode)) { r.code = "0"; } else { r.code = responseCode; } + final Schema responseSchema = getSchemaFromResponse(response); + r.schema = responseSchema; r.message = escapeText(response.getDescription()); - r.schema = response.getSchema(); - r.examples = toExamples(response.getExamples()); + // TODO need to revise and test examples in responses + // ApiResponse does not support examples at the moment + //r.examples = toExamples(response.getExamples()); r.jsonSchema = Json.pretty(response); - r.vendorExtensions = response.getVendorExtensions(); + if (response.getExtensions() != null && !response.getExtensions().isEmpty()) { + r.vendorExtensions.putAll(response.getExtensions()); + } addHeaders(response, r.headers); r.hasHeaders = !r.headers.isEmpty(); if (r.schema != null) { - Property responseProperty = response.getSchema(); - responseProperty.setRequired(true); - CodegenProperty cm = fromProperty("response", responseProperty); + CodegenProperty cp = fromProperty("response", responseSchema); - if (responseProperty instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) responseProperty; - CodegenProperty innerProperty = fromProperty("response", ap.getItems()); + if (ModelUtils.isArraySchema(responseSchema)) { + ArraySchema as = (ArraySchema) responseSchema; + CodegenProperty innerProperty = fromProperty("response", as.getItems()); r.baseType = innerProperty.baseType; } else { - if (cm.complexType != null) { - r.baseType = cm.complexType; + if (cp.complexType != null) { + r.baseType = cp.complexType; } else { - r.baseType = cm.baseType; + r.baseType = cp.baseType; } } - r.dataType = cm.datatype; - if (Boolean.TRUE.equals(cm.isString) && Boolean.TRUE.equals(cm.isUuid)) { + r.dataType = cp.datatype; + + if (Boolean.TRUE.equals(cp.isString) && Boolean.TRUE.equals(cp.isUuid)) { r.isUuid = true; - } else if (Boolean.TRUE.equals(cm.isByteArray)) { + } else if (Boolean.TRUE.equals(cp.isByteArray)) { r.isByteArray = true; - } else if (Boolean.TRUE.equals(cm.isString)) { + r.isFile = true; // in OAS3.0 "file" is 'byte' (format) + } else if (Boolean.TRUE.equals(cp.isString)) { r.isString = true; - } else if (Boolean.TRUE.equals(cm.isBoolean)) { + } else if (Boolean.TRUE.equals(cp.isBoolean)) { r.isBoolean = true; - } else if (Boolean.TRUE.equals(cm.isLong)) { + } else if (Boolean.TRUE.equals(cp.isLong)) { r.isLong = true; r.isNumeric = true; - } else if (Boolean.TRUE.equals(cm.isInteger)) { + } else if (Boolean.TRUE.equals(cp.isInteger)) { r.isInteger = true; r.isNumeric = true; - } else if (Boolean.TRUE.equals(cm.isNumber)) { + } else if (Boolean.TRUE.equals(cp.isNumber)) { r.isNumber = true; r.isNumeric = true; - } else if (Boolean.TRUE.equals(cm.isDouble)) { + } else if (Boolean.TRUE.equals(cp.isDouble)) { r.isDouble = true; r.isNumeric = true; - } else if (Boolean.TRUE.equals(cm.isFloat)) { + } else if (Boolean.TRUE.equals(cp.isFloat)) { r.isFloat = true; r.isNumeric = true; - } else if (Boolean.TRUE.equals(cm.isBinary)) { + } else if (Boolean.TRUE.equals(cp.isBinary)) { r.isBinary = true; - } else if (Boolean.TRUE.equals(cm.isFile)) { + } else if (Boolean.TRUE.equals(cp.isFile)) { r.isFile = true; - } else if (Boolean.TRUE.equals(cm.isDate)) { + } else if (Boolean.TRUE.equals(cp.isDate)) { r.isDate = true; - } else if (Boolean.TRUE.equals(cm.isDateTime)) { + } else if (Boolean.TRUE.equals(cp.isDateTime)) { r.isDateTime = true; } else { - LOGGER.debug("Property type is not primitive: " + cm.datatype); + LOGGER.debug("Property type is not primitive: " + cp.datatype); } - if (cm.isContainer) { + if (cp.isContainer) { r.simpleType = false; - r.containerType = cm.containerType; - r.isMapContainer = "map".equals(cm.containerType); - r.isListContainer = "list".equalsIgnoreCase(cm.containerType) || "array".equalsIgnoreCase(cm.containerType); + r.containerType = cp.containerType; + r.isMapContainer = "map".equals(cp.containerType); + r.isListContainer = "list".equalsIgnoreCase(cp.containerType) || "array".equalsIgnoreCase(cp.containerType); } else { r.simpleType = true; } + r.primitiveType = (r.baseType == null || languageSpecificPrimitives().contains(r.baseType)); } + if (r.baseType == null) { r.isMapContainer = false; r.isListContainer = false; r.primitiveType = true; r.simpleType = true; } + return r; } /** - * Convert Swagger Parameter object to Codegen Parameter object + * Convert OAS Parameter object to Codegen Parameter object * - * @param param Swagger parameter object - * @param imports set of imports for library/package/module + * @param parameter OAS parameter object + * @param imports set of imports for library/package/module * @return Codegen Parameter object */ - public CodegenParameter fromParameter(Parameter param, Set imports) { - CodegenParameter p = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); - p.baseName = param.getName(); - p.description = escapeText(param.getDescription()); - p.unescapedDescription = param.getDescription(); - if (param.getRequired()) { - p.required = param.getRequired(); + public CodegenParameter fromParameter(Parameter parameter, Set imports) { + CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); + codegenParameter.baseName = parameter.getName(); + codegenParameter.description = escapeText(parameter.getDescription()); + codegenParameter.unescapedDescription = parameter.getDescription(); + if (parameter.getRequired() != null) { + codegenParameter.required = parameter.getRequired(); } - p.jsonSchema = Json.pretty(param); + codegenParameter.jsonSchema = Json.pretty(parameter); if (System.getProperty("debugParser") != null) { - LOGGER.info("working on Parameter " + param.getName()); + LOGGER.info("working on Parameter " + parameter.getName()); + LOGGER.info("JSON schema: " + codegenParameter.jsonSchema); } + // TODO need to revise the logic below // move the defaultValue for headers, forms and params + /* if (param instanceof QueryParameter) { - QueryParameter qp = (QueryParameter) param; - if(qp.getDefaultValue() != null) { - p.defaultValue = qp.getDefaultValue().toString(); + QueryParameter qp = (QueryParameter) parameter; + if (qp.getDefaultValue() != null) { + codegenParameter.defaultValue = qp.getDefaultValue().toString(); } } else if (param instanceof HeaderParameter) { - HeaderParameter hp = (HeaderParameter) param; - if(hp.getDefaultValue() != null) { - p.defaultValue = hp.getDefaultValue().toString(); + HeaderParameter hp = (HeaderParameter) parameter; + if (hp.getDefaultValue() != null) { + codegenParameter.defaultValue = hp.getDefaultValue().toString(); } } else if (param instanceof FormParameter) { - FormParameter fp = (FormParameter) param; - if(fp.getDefaultValue() != null) { - p.defaultValue = fp.getDefaultValue().toString(); + FormParameter fp = (FormParameter) parameter; + if (fp.getDefaultValue() != null) { + codegenParameter.defaultValue = fp.getDefaultValue().toString(); } - } + }*/ - p.vendorExtensions = param.getVendorExtensions(); + if (parameter.getExtensions() != null && !parameter.getExtensions().isEmpty()) { + codegenParameter.vendorExtensions.putAll(parameter.getExtensions()); + } - if (param instanceof SerializableParameter) { - SerializableParameter qp = (SerializableParameter) param; - Property property; + if (parameter.getSchema() != null) { + Schema parameterSchema = parameter.getSchema(); + // TDOO revise collectionFormat String collectionFormat = null; - String type = qp.getType(); - if (null == type) { - LOGGER.warn("Type is NULL for Serializable Parameter: " + param.getName()); - } - if ("array".equals(type)) { // for array parameter - Property inner = qp.getItems(); + if (ModelUtils.isArraySchema(parameterSchema)) { // for array parameter + final ArraySchema arraySchema = (ArraySchema) parameterSchema; + Schema inner = arraySchema.getItems(); if (inner == null) { - LOGGER.warn("warning! No inner type supplied for array parameter \"" + qp.getName() + "\", using String"); - inner = new StringProperty().description("//TODO automatically added by swagger-codegen"); - } - property = new ArrayProperty(inner); - collectionFormat = qp.getCollectionFormat(); - if (collectionFormat == null) { - collectionFormat = "csv"; + LOGGER.warn("warning! No inner type supplied for array parameter \"" + parameter.getName() + "\", using String"); + inner = new StringSchema().description("//TODO automatically added by openapi-generator due to missing iner type definition in the spec"); + arraySchema.setItems(inner); } - CodegenProperty pr = fromProperty("inner", inner); - p.items = pr; - p.baseType = pr.datatype; - p.isContainer = true; - p.isListContainer = true; + + collectionFormat = getCollectionFormat(parameter); + CodegenProperty codegenProperty = fromProperty("inner", inner); + codegenParameter.items = codegenProperty; + codegenParameter.baseType = codegenProperty.datatype; + codegenParameter.isContainer = true; + codegenParameter.isListContainer = true; + // recursively add import - while (pr != null) { - imports.add(pr.baseType); - pr = pr.items; - } - } else if ("object".equals(type)) { // for map parameter - Property inner = qp.getItems(); - if (inner == null) { - LOGGER.warn("warning! No inner type supplied for map parameter \"" + qp.getName() + "\", using String"); - inner = new StringProperty().description("//TODO automatically added by swagger-codegen"); + while (codegenProperty != null) { + imports.add(codegenProperty.baseType); + codegenProperty = codegenProperty.items; } - property = new MapProperty(inner); - collectionFormat = qp.getCollectionFormat(); - CodegenProperty pr = fromProperty("inner", inner); - p.items = pr; - p.baseType = pr.datatype; - p.isContainer = true; - p.isMapContainer = true; + + } else if (ModelUtils.isMapSchema(parameterSchema)) { // for map parameter + CodegenProperty codegenProperty = fromProperty("inner", (Schema) parameterSchema.getAdditionalProperties()); + codegenParameter.items = codegenProperty; + codegenParameter.baseType = codegenProperty.datatype; + codegenParameter.isContainer = true; + codegenParameter.isMapContainer = true; + collectionFormat = getCollectionFormat(parameter); + // recursively add import - while (pr != null) { - imports.add(pr.baseType); - pr = pr.items; + while (codegenProperty != null) { + imports.add(codegenProperty.baseType); + codegenProperty = codegenProperty.items; } + } +/* TODO revise the logic below } else { Map args = new HashMap(); String format = qp.getFormat(); args.put(PropertyId.ENUM, qp.getEnum()); property = PropertyBuilder.build(type, format, args); } - - if (property == null) { - LOGGER.warn("warning! Property type \"" + type + "\" not found for parameter \"" + param.getName() + "\", using String"); - property = new StringProperty().description("//TODO automatically added by swagger-codegen. Type was " + type + " but not supported"); +*/ + if (parameterSchema == null) { + 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."); } - property.setRequired(param.getRequired()); - CodegenProperty cp = fromProperty(qp.getName(), property); + CodegenProperty codegenProperty = fromProperty(parameter.getName(), parameterSchema); + // TODO revise below which seems not working + //if (parameterSchema.getRequired() != null && !parameterSchema.getRequired().isEmpty() && parameterSchema.getRequired().contains(codegenProperty.baseName)) { + codegenProperty.required = Boolean.TRUE.equals(parameter.getRequired()) ? true : false; + //} + //codegenProperty.required = true; // set boolean flag (e.g. isString) - setParameterBooleanFlagWithCodegenProperty(p, cp); + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + - String parameterDataType = this.getParameterDataType(param, property); + String parameterDataType = this.getParameterDataType(parameter, parameterSchema); if (parameterDataType != null) { - p.dataType = parameterDataType; + codegenParameter.dataType = parameterDataType; } else { - p.dataType = cp.datatype; + codegenParameter.dataType = codegenProperty.datatype; } - p.dataFormat = cp.dataFormat; - if(cp.isEnum) { - p.datatypeWithEnum = cp.datatypeWithEnum; - p.enumName = cp.enumName; + codegenParameter.dataFormat = codegenProperty.dataFormat; + codegenParameter.required = codegenProperty.required; + + if (codegenProperty.isEnum) { + codegenParameter.datatypeWithEnum = codegenProperty.datatypeWithEnum; + codegenParameter.enumName = codegenProperty.enumName; } // enum - updateCodegenPropertyEnum(cp); - p.isEnum = cp.isEnum; - p._enum = cp._enum; - p.allowableValues = cp.allowableValues; - - - if (cp.items != null && cp.items.isEnum) { - p.datatypeWithEnum = cp.datatypeWithEnum; - p.enumName = cp.enumName; - p.items = cp.items; + updateCodegenPropertyEnum(codegenProperty); + codegenParameter.isEnum = codegenProperty.isEnum; + codegenParameter._enum = codegenProperty._enum; + codegenParameter.allowableValues = codegenProperty.allowableValues; + + if (codegenProperty.items != null && codegenProperty.items.isEnum) { + codegenParameter.datatypeWithEnum = codegenProperty.datatypeWithEnum; + codegenParameter.enumName = codegenProperty.enumName; + codegenParameter.items = codegenProperty.items; } - p.collectionFormat = collectionFormat; - if(collectionFormat != null && collectionFormat.equals("multi")) { - p.isCollectionFormatMulti = true; + + codegenParameter.collectionFormat = collectionFormat; + if ("multi".equals(collectionFormat)) { + codegenParameter.isCollectionFormatMulti = true; } - p.paramName = toParamName(qp.getName()); + codegenParameter.paramName = toParamName(parameter.getName()); // import - if (cp.complexType != null) { - imports.add(cp.complexType); + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); } // validation // handle maximum, minimum properly for int/long by removing the trailing ".0" - if ("integer".equals(qp.getType())) { - p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum().longValue()); - p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum().longValue()); + if (ModelUtils.isIntegerSchema(parameterSchema)) { + codegenParameter.maximum = parameterSchema.getMaximum() == null ? null : String.valueOf(parameterSchema.getMaximum().longValue()); + codegenParameter.minimum = parameterSchema.getMinimum() == null ? null : String.valueOf(parameterSchema.getMinimum().longValue()); } else { - p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum()); - p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum()); + codegenParameter.maximum = parameterSchema.getMaximum() == null ? null : String.valueOf(parameterSchema.getMaximum()); + codegenParameter.minimum = parameterSchema.getMinimum() == null ? null : String.valueOf(parameterSchema.getMinimum()); } - p.exclusiveMaximum = qp.isExclusiveMaximum() == null ? false : qp.isExclusiveMaximum(); - p.exclusiveMinimum = qp.isExclusiveMinimum() == null ? false : qp.isExclusiveMinimum(); - p.maxLength = qp.getMaxLength(); - p.minLength = qp.getMinLength(); - p.pattern = toRegularExpression(qp.getPattern()); - p.maxItems = qp.getMaxItems(); - p.minItems = qp.getMinItems(); - p.uniqueItems = qp.isUniqueItems() == null ? false : qp.isUniqueItems(); - p.multipleOf = qp.getMultipleOf(); + codegenParameter.exclusiveMaximum = parameterSchema.getExclusiveMaximum() == null ? false : parameterSchema.getExclusiveMaximum(); + codegenParameter.exclusiveMinimum = parameterSchema.getExclusiveMinimum() == null ? false : parameterSchema.getExclusiveMinimum(); + codegenParameter.maxLength = parameterSchema.getMaxLength(); + codegenParameter.minLength = parameterSchema.getMinLength(); + codegenParameter.pattern = toRegularExpression(parameterSchema.getPattern()); + codegenParameter.maxItems = parameterSchema.getMaxItems(); + codegenParameter.minItems = parameterSchema.getMinItems(); + codegenParameter.uniqueItems = parameterSchema.getUniqueItems() == null ? false : parameterSchema.getUniqueItems(); + codegenParameter.multipleOf = parameterSchema.getMultipleOf(); // exclusive* are noop without corresponding min/max - if (p.maximum != null || p.minimum != null || - p.maxLength != null || p.minLength != null || - p.maxItems != null || p.minItems != null || - p.pattern != null) { - p.hasValidation = true; + if (codegenParameter.maximum != null || codegenParameter.minimum != null || + codegenParameter.maxLength != null || codegenParameter.minLength != null || + codegenParameter.maxItems != null || codegenParameter.minItems != null || + codegenParameter.pattern != null) { + codegenParameter.hasValidation = true; } } else { - if (!(param instanceof BodyParameter)) { - LOGGER.error("Cannot use Parameter " + param + " as Body Parameter"); + LOGGER.error("ERROR! Not handling " + parameter + " as Body Parameter at the moment"); + /* TODO need to revise the logic below to handle body parameter + if (!(parameter instanceof BodyParameter)) { + LOGGER.error("Cannot use Parameter " + parameter + " as Body Parameter"); } BodyParameter bp = (BodyParameter) param; @@ -2590,7 +2601,7 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { ModelImpl impl = (ModelImpl) model; CodegenModel cm = fromModel(bp.getName(), impl); if (!cm.emptyVars) { - p.dataType = getTypeDeclaration(cm.classname); + codegen.dataType = getTypeDeclaration(cm.classname); imports.add(p.dataType); } else { Property prop = PropertyBuilder.build(impl.getType(), impl.getFormat(), null); @@ -2662,87 +2673,81 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { } } p.paramName = toParamName(bp.getName()); + */ } // Issue #2561 (neilotoole) : Set the isParam flags. // This code has been moved to here from #fromOperation // because these values should be set before calling #postProcessParameter. // See: https://github.com/swagger-api/swagger-codegen/issues/2561 - if (param instanceof QueryParameter) { - p.isQueryParam = true; - } else if (param instanceof PathParameter) { - p.required = true; - p.isPathParam = true; - } else if (param instanceof HeaderParameter) { - p.isHeaderParam = true; - } else if (param instanceof CookieParameter) { - p.isCookieParam = true; - } else if (param instanceof BodyParameter) { - p.isBodyParam = true; - p.isBinary = isDataTypeBinary(p.dataType); - } else if (param instanceof FormParameter) { - if ("file".equalsIgnoreCase(((FormParameter) param).getType()) || "file".equals(p.baseType)) { - p.isFile = true; - } else { - p.notFile = true; - } - p.isFormParam = true; + if (parameter instanceof QueryParameter || "query".equalsIgnoreCase(parameter.getIn())) { + codegenParameter.isQueryParam = true; + } else if (parameter instanceof PathParameter || "path".equalsIgnoreCase(parameter.getIn())) { + codegenParameter.required = true; + codegenParameter.isPathParam = true; + } else if (parameter instanceof HeaderParameter || "header".equalsIgnoreCase(parameter.getIn())) { + codegenParameter.isHeaderParam = true; + } else if (parameter instanceof CookieParameter || "cookie".equalsIgnoreCase(parameter.getIn())) { + codegenParameter.isCookieParam = true; + } else { + LOGGER.warn("Unknown parameter type: " + parameter.getName()); } // set the example value // if not specified in x-example, generate a default value - if (p.vendorExtensions.containsKey("x-example")) { - p.example = Json.pretty(p.vendorExtensions.get("x-example")); - } else if (Boolean.TRUE.equals(p.isUuid) && (Boolean.TRUE.equals(p.isString))) { - p.example = "38400000-8cf0-11bd-b23e-10b96e4ef00d"; - } else if (Boolean.TRUE.equals(p.isString)) { - p.example = p.paramName + "_example"; - } else if (Boolean.TRUE.equals(p.isBoolean)) { - p.example = "true"; - } else if (Boolean.TRUE.equals(p.isLong)) { - p.example = "789"; - } else if (Boolean.TRUE.equals(p.isInteger)) { - p.example = "56"; - } else if (Boolean.TRUE.equals(p.isFloat)) { - p.example = "3.4"; - } else if (Boolean.TRUE.equals(p.isNumber)) { - p.example = "8.14"; - } else if (Boolean.TRUE.equals(p.isDouble)) { - p.example = "1.2"; - } else if (Boolean.TRUE.equals(p.isBinary)) { - p.example = "BINARY_DATA_HERE"; - } else if (Boolean.TRUE.equals(p.isByteArray)) { - p.example = "B"; - } else if (Boolean.TRUE.equals(p.isFile)) { - p.example = "/path/to/file.txt"; - } else if (Boolean.TRUE.equals(p.isDate)) { - p.example = "2013-10-20"; - } else if (Boolean.TRUE.equals(p.isDateTime)) { - p.example = "2013-10-20T19:20:30+01:00"; - } else if (Boolean.TRUE.equals(p.isFile)) { - p.example = "/path/to/file.txt"; + // TODO need to revise how to obtain the example value + if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) { + codegenParameter.example = Json.pretty(codegenParameter.vendorExtensions.get("x-example")); + } else if (Boolean.TRUE.equals(codegenParameter.isString)) { + codegenParameter.example = codegenParameter.paramName + "_example"; + } else if (Boolean.TRUE.equals(codegenParameter.isBoolean)) { + codegenParameter.example = "true"; + } else if (Boolean.TRUE.equals(codegenParameter.isLong)) { + codegenParameter.example = "789"; + } else if (Boolean.TRUE.equals(codegenParameter.isInteger)) { + codegenParameter.example = "56"; + } else if (Boolean.TRUE.equals(codegenParameter.isFloat)) { + codegenParameter.example = "3.4"; + } else if (Boolean.TRUE.equals(codegenParameter.isDouble)) { + codegenParameter.example = "1.2"; + } else if (Boolean.TRUE.equals(codegenParameter.isBinary)) { + codegenParameter.example = "BINARY_DATA_HERE"; + } else if (Boolean.TRUE.equals(codegenParameter.isByteArray)) { + codegenParameter.example = "B"; + } else if (Boolean.TRUE.equals(codegenParameter.isFile)) { + codegenParameter.example = "/path/to/file.txt"; + } else if (Boolean.TRUE.equals(codegenParameter.isDate)) { + codegenParameter.example = "2013-10-20"; + } else if (Boolean.TRUE.equals(codegenParameter.isDateTime)) { + codegenParameter.example = "2013-10-20T19:20:30+01:00"; + } else if (Boolean.TRUE.equals(codegenParameter.isUuid)) { + codegenParameter.example = "38400000-8cf0-11bd-b23e-10b96e4ef00d"; + } else if (Boolean.TRUE.equals(codegenParameter.isFile)) { + codegenParameter.example = "/path/to/file.txt"; } // set the parameter excample value // should be overridden by lang codegen - setParameterExampleValue(p); + setParameterExampleValue(codegenParameter); - postProcessParameter(p); - return p; + postProcessParameter(codegenParameter); + LOGGER.debug("debugging codegenParameter return: " + codegenParameter); + return codegenParameter; } - /** - * Returns the data type of a parameter. - * Returns null by default to use the CodegenProperty.datatype value - * @param parameter - * @param property - * @return - */ - protected String getParameterDataType(Parameter parameter, Property property) { + /** + * Returns the data type of a parameter. + * Returns null by default to use the CodegenProperty.datatype value + * + * @param parameter Parameter + * @param schema Schema + * @return data type + */ + protected String getParameterDataType(Parameter parameter, Schema schema) { return null; - } - + } + // TODO revise below as it should be replaced by ModelUtils.isByteArraySchema(parameterSchema) public boolean isDataTypeBinary(String dataType) { if (dataType != null) { return dataType.toLowerCase().startsWith("byte"); @@ -2751,6 +2756,7 @@ public boolean isDataTypeBinary(String dataType) { } } + // TODO revise below as it should be replaced by ModelUtils.isFileSchema(parameterSchema) public boolean isDataTypeFile(String dataType) { if (dataType != null) { return dataType.toLowerCase().equals("file"); @@ -2760,103 +2766,81 @@ public boolean isDataTypeFile(String dataType) { } /** - * Convert map of Swagger SecuritySchemeDefinition objects to a list of Codegen Security objects + * Convert map of OAS SecurityScheme objects to a list of Codegen Security objects * - * @param schemes a map of Swagger SecuritySchemeDefinition object + * @param securitySchemeMap a map of OAS SecuritySchemeDefinition object * @return a list of Codegen Security objects */ @SuppressWarnings("static-method") - public List fromSecurity(Map schemes) { - if (schemes == null) { + public List fromSecurity(Map securitySchemeMap) { + if (securitySchemeMap == null) { return Collections.emptyList(); } - List secs = new ArrayList(schemes.size()); - for (Iterator> it = schemes.entrySet().iterator(); it.hasNext(); ) { - final Map.Entry entry = it.next(); - final SecuritySchemeDefinition schemeDefinition = entry.getValue(); - - CodegenSecurity sec = CodegenModelFactory.newInstance(CodegenModelType.SECURITY); - sec.name = entry.getKey(); - sec.type = schemeDefinition.getType(); - sec.isCode = sec.isPassword = sec.isApplication = sec.isImplicit = false; - sec.vendorExtensions = schemeDefinition.getVendorExtensions(); - - if (schemeDefinition instanceof ApiKeyAuthDefinition) { - final ApiKeyAuthDefinition apiKeyDefinition = (ApiKeyAuthDefinition) schemeDefinition; - sec.isBasic = sec.isOAuth = false; - sec.isApiKey = true; - sec.keyParamName = apiKeyDefinition.getName(); - sec.isKeyInHeader = apiKeyDefinition.getIn() == In.HEADER; - sec.isKeyInQuery = !sec.isKeyInHeader; - } else if(schemeDefinition instanceof BasicAuthDefinition) { - sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isOAuth = false; - sec.isBasic = true; - } else { - final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; - sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; - sec.isOAuth = true; - sec.flow = oauth2Definition.getFlow(); - if (sec.flow == null) { - throw new RuntimeException("missing oauth flow in " + sec.name); + List codegenSecurities = new ArrayList(securitySchemeMap.size()); + for (String key : securitySchemeMap.keySet()) { + final SecurityScheme securityScheme = securitySchemeMap.get(key); + + CodegenSecurity cs = CodegenModelFactory.newInstance(CodegenModelType.SECURITY); + cs.name = key; + cs.type = securityScheme.getType().toString(); + cs.isCode = cs.isPassword = cs.isApplication = cs.isImplicit = false; + + if (SecurityScheme.Type.APIKEY.equals(securityScheme.getType())) { + cs.isBasic = cs.isOAuth = false; + cs.isApiKey = true; + cs.keyParamName = securityScheme.getName(); + cs.isKeyInHeader = securityScheme.getIn() == SecurityScheme.In.HEADER; + cs.isKeyInQuery = !cs.isKeyInHeader; + } else if (SecurityScheme.Type.HTTP.equals(securityScheme.getType())) { + cs.isKeyInHeader = cs.isKeyInQuery = cs.isApiKey = cs.isOAuth = false; + cs.isBasic = true; + } else if (SecurityScheme.Type.OAUTH2.equals(securityScheme.getType())) { + cs.isKeyInHeader = cs.isKeyInQuery = cs.isApiKey = cs.isBasic = false; + cs.isOAuth = true; + final OAuthFlows flows = securityScheme.getFlows(); + if (securityScheme.getFlows() == null) { + throw new RuntimeException("missing oauth flow in " + cs.name); } - switch(sec.flow) { - case "accessCode": - sec.isCode = true; - break; - case "password": - sec.isPassword = true; - break; - case "application": - sec.isApplication = true; - break; - case "implicit": - sec.isImplicit = true; - break; - default: - throw new RuntimeException("unknown oauth flow: " + sec.flow); - } - sec.authorizationUrl = oauth2Definition.getAuthorizationUrl(); - sec.tokenUrl = oauth2Definition.getTokenUrl(); - if (oauth2Definition.getScopes() != null) { - List> scopes = new ArrayList>(); - int count = 0, numScopes = oauth2Definition.getScopes().size(); - for(Map.Entry scopeEntry : oauth2Definition.getScopes().entrySet()) { - Map scope = new HashMap(); - scope.put("scope", scopeEntry.getKey()); - scope.put("description", escapeText(scopeEntry.getValue())); - - count += 1; - if (count < numScopes) { - scope.put("hasMore", "true"); - } else { - scope.put("hasMore", null); - } - - scopes.add(scope); - } - sec.scopes = scopes; + if (flows.getPassword() != null) { + setOauth2Info(cs, flows.getPassword()); + cs.isPassword = true; + cs.flow = "password"; + } else if (flows.getImplicit() != null) { + setOauth2Info(cs, flows.getImplicit()); + cs.isImplicit = true; + cs.flow = "implicit"; + } else if (flows.getClientCredentials() != null) { + setOauth2Info(cs, flows.getClientCredentials()); + cs.isApplication = true; + cs.flow = "application"; + } else if (flows.getAuthorizationCode() != null) { + setOauth2Info(cs, flows.getAuthorizationCode()); + cs.isCode = true; + cs.flow = "accessCode"; + } else { + throw new RuntimeException("Could not identify any oauth2 flow in " + cs.name); } } - secs.add(sec); + codegenSecurities.add(cs); } // sort auth methods to maintain the same order - Collections.sort(secs, new Comparator() { + Collections.sort(codegenSecurities, new Comparator() { @Override public int compare(CodegenSecurity one, CodegenSecurity another) { return ObjectUtils.compare(one.name, another.name); } }); // set 'hasMore' - Iterator it = secs.iterator(); + Iterator it = codegenSecurities.iterator(); while (it.hasNext()) { final CodegenSecurity security = it.next(); security.hasMore = it.hasNext(); } - return secs; + return codegenSecurities; } protected void setReservedWordsLowerCase(List words) { @@ -2873,8 +2857,8 @@ protected boolean isReservedWord(String word) { /** * Get operationId from the operation object, and if it's blank, generate a new one from the given parameters. * - * @param operation the operation object - * @param path the path of the operation + * @param operation the operation object + * @param path the path of the operation * @param httpMethod the HTTP method of the operation * @return the (generated) operationId */ @@ -2914,7 +2898,7 @@ protected String getOrGenerateOperationId(Operation operation, String path, Stri */ protected boolean needToImport(String type) { return StringUtils.isNotBlank(type) && !defaultIncludes.contains(type) - && !languageSpecificPrimitives.contains(type); + && !languageSpecificPrimitives.contains(type); } @SuppressWarnings("static-method") @@ -2933,10 +2917,16 @@ protected List> toExamples(Map examples) { return output; } - private void addHeaders(Response response, List target) { + /** + * Add headers to codegen property + * + * @param response API response + * @param target list of codegen property + */ + private void addHeaders(ApiResponse response, List properties) { if (response.getHeaders() != null) { - for (Map.Entry headers : response.getHeaders().entrySet()) { - target.add(fromProperty(headers.getKey(), headers.getValue())); + for (Map.Entry headers : response.getHeaders().entrySet()) { + properties.add(fromProperty(headers.getKey(), headers.getValue().getSchema())); } } } @@ -2972,11 +2962,11 @@ private static Map addHasMore(Map objs) { /** * Add operation to group * - * @param tag name of the tag + * @param tag name of the tag * @param resourcePath path of the resource - * @param operation Swagger Operation object - * @param co Codegen Operation object - * @param operations map of Codegen operations + * @param operation OAS Operation object + * @param co Codegen Operation object + * @param operations map of Codegen operations */ @SuppressWarnings("static-method") public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { @@ -2986,16 +2976,15 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera operations.put(tag, opList); } // check for operationId uniqueness - String uniqueName = co.operationId; int counter = 0; - for(CodegenOperation op : opList) { - if(uniqueName.equals(op.operationId)) { + for (CodegenOperation op : opList) { + if (uniqueName.equals(op.operationId)) { uniqueName = co.operationId + "_" + counter; - counter ++; + counter++; } } - if(!co.operationId.equals(uniqueName)) { + if (!co.operationId.equals(uniqueName)) { LOGGER.warn("generated unique operationId `" + uniqueName + "`"); } co.operationId = uniqueName; @@ -3006,18 +2995,20 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera co.baseName = tag; } - private void addParentContainer(CodegenModel m, String name, Property property) { - final CodegenProperty tmp = fromProperty(name, property); - addImport(m, tmp.complexType); - m.parent = toInstantiationType(property); - final String containerType = tmp.containerType; + + private void addParentContainer(CodegenModel model, String name, Schema schema) { + final CodegenProperty property = fromProperty(name, schema); + addImport(model, property.complexType); + model.parent = toInstantiationType(schema); + final String containerType = property.containerType; final String instantiationType = instantiationTypes.get(containerType); if (instantiationType != null) { - addImport(m, instantiationType); + addImport(model, instantiationType); } + final String mappedType = typeMapping.get(containerType); if (mappedType != null) { - addImport(m, mappedType); + addImport(model, mappedType); } } @@ -3061,9 +3052,9 @@ protected String dashize(String word) { /** * Generate the next name for the given name, i.e. append "2" to the base name if not ending with a number, * otherwise increase the number by 1. For example: - * status => status2 - * status2 => status3 - * myName100 => myName101 + * status => status2 + * status2 => status3 + * myName100 => myName101 * * @param name The base name * @return The next name for the base name @@ -3086,20 +3077,19 @@ protected void addImport(CodegenModel m, String type) { } } - private void addVars(CodegenModel m, Map properties, List required) { - addVars(m, properties, required, null, null); + private void addVars(CodegenModel model, Map properties, List required) { + addVars(model, properties, required, null, null); } - private void addVars(CodegenModel m, Map properties, List required, - Map allProperties, List allRequired) { + private void addVars(CodegenModel m, Map properties, List required, + Map allProperties, List allRequired) { m.hasRequired = false; if (properties != null && !properties.isEmpty()) { m.hasVars = true; m.hasEnums = false; - - Set mandatory = required == null ? Collections. emptySet() + Set mandatory = required == null ? Collections.emptySet() : new TreeSet(required); addVars(m, m.vars, properties, mandatory); m.allMandatory = m.mandatory = mandatory; @@ -3110,28 +3100,28 @@ private void addVars(CodegenModel m, Map properties, List allMandatory = allRequired == null ? Collections. emptySet() + Set allMandatory = allRequired == null ? Collections.emptySet() : new TreeSet(allRequired); addVars(m, m.allVars, allProperties, allMandatory); m.allMandatory = allMandatory; } } - private void addVars(CodegenModel m, List vars, Map properties, Set mandatory) { + private void addVars(CodegenModel m, List vars, Map properties, Set mandatory) { // convert set to list so that we can access the next entry in the loop - List> propertyList = new ArrayList>(properties.entrySet()); + List> propertyList = new ArrayList>(properties.entrySet()); final int totalCount = propertyList.size(); for (int i = 0; i < totalCount; i++) { - Map.Entry entry = propertyList.get(i); + Map.Entry entry = propertyList.get(i); final String key = entry.getKey(); - final Property prop = entry.getValue(); + final Schema prop = entry.getValue(); if (prop == null) { LOGGER.warn("null property for " + key); } else { final CodegenProperty cp = fromProperty(key, prop); - cp.required = mandatory.contains(key) ? true : false; + cp.required = mandatory.contains(key); m.hasRequired = m.hasRequired || cp.required; m.hasOptional = m.hasOptional || !cp.required; if (cp.isEnum) { @@ -3145,10 +3135,10 @@ private void addVars(CodegenModel m, List vars, Map vars, Map vars, Map getAllAliases(Map allDefinitions) { + private static Map getAllAliases(Map schemas) { + if (schemas == null || schemas.isEmpty()) { + return new HashMap<>(); + } + Map aliases = new HashMap<>(); - if (allDefinitions != null) { - for (Map.Entry entry : allDefinitions.entrySet()) { - String swaggerName = entry.getKey(); - Model m = entry.getValue(); - if (m instanceof ModelImpl) { - ModelImpl impl = (ModelImpl) m; - if (impl.getType() != null && - !impl.getType().equals("object") && - impl.getEnum() == null) { - aliases.put(swaggerName, impl.getType()); - } - } + for (Map.Entry entry : schemas.entrySet()) { + String oasName = entry.getKey(); + Schema schema = entry.getValue(); + if (schema.getType() != null && !schema.getType().equals("object") && schema.getEnum() == null) { + aliases.put(oasName, schema.getType()); } } + return aliases; } @@ -3222,7 +3211,7 @@ public String removeNonNameElementToCamelCase(String name) { /** * Remove characters that is not good to be included in method name from the input and camelize it * - * @param name string to be camelize + * @param name string to be camelize * @param nonNameElementPattern a regex pattern of the characters that is not good to be included in name * @return camelized string */ @@ -3255,7 +3244,7 @@ public static String camelize(String word) { /** * Camelize name (parameter, property, method, etc) * - * @param word string to be camelize + * @param word string to be camelize * @param lowercaseFirstLetter lower case for first letter if set to true * @return camelized string */ @@ -3319,6 +3308,9 @@ public static String camelize(String word, boolean lowercaseFirstLetter) { word = word.substring(0, 1).toLowerCase() + word.substring(1); } + // remove all underscore + word = word.replaceAll("_", ""); + return word; } @@ -3331,8 +3323,7 @@ public String apiFilename(String templateName, String tag) { * Return the full path and API documentation file * * @param templateName template name - * @param tag tag - * + * @param tag tag * @return the API documentation file name with full path */ public String apiDocFilename(String templateName, String tag) { @@ -3344,8 +3335,7 @@ public String apiDocFilename(String templateName, String tag) { * Return the full path and API test file * * @param templateName template name - * @param tag tag - * + * @param tag tag * @return the API test file name with full path */ public String apiTestFilename(String templateName, String tag) { @@ -3373,9 +3363,18 @@ public void setRemoveOperationIdPrefix(boolean removeOperationIdPrefix) { this.removeOperationIdPrefix = removeOperationIdPrefix; } + public boolean isHideGenerationTimestamp() { + return hideGenerationTimestamp; + } + + public void setHideGenerationTimestamp(boolean hideGenerationTimestamp) { + this.hideGenerationTimestamp = hideGenerationTimestamp; + } + /** * All library templates supported. * (key: library name, value: library description) + * * @return the supported libraries */ public Map supportedLibraries() { @@ -3390,7 +3389,7 @@ public Map supportedLibraries() { public void setLibrary(String library) { if (library != null && !supportedLibraries.containsKey(library)) { StringBuilder sb = new StringBuilder("Unknown library: " + library + "\nAvailable libraries:"); - if(supportedLibraries.size() == 0) { + if (supportedLibraries.size() == 0) { sb.append("\n ").append("NONE"); } else { for (String lib : supportedLibraries.keySet()) { @@ -3540,8 +3539,7 @@ public String sanitizeName(String name) { // $php_variable => php_variable if (allowUnicodeIdentifiers) { //could be converted to a single line with ?: operator name = Pattern.compile("\\W", Pattern.UNICODE_CHARACTER_CLASS).matcher(name).replaceAll(""); - } - else { + } else { name = name.replaceAll("\\W", ""); } @@ -3568,23 +3566,22 @@ public String sanitizeTag(String tag) { /** * Only write if the file doesn't exist * - * @param outputFolder Output folder + * @param outputFolder Output folder * @param supportingFile Supporting file */ public void writeOptional(String outputFolder, SupportingFile supportingFile) { String folder = ""; - if(outputFolder != null && !"".equals(outputFolder)) { + if (outputFolder != null && !"".equals(outputFolder)) { folder += outputFolder + File.separator; } folder += supportingFile.folder; - if(!"".equals(folder)) { + if (!"".equals(folder)) { folder += File.separator + supportingFile.destinationFilename; - } - else { + } else { folder = supportingFile.destinationFilename; } - if(!new File(folder).exists()) { + if (!new File(folder).exists()) { supportingFiles.add(supportingFile); } else { LOGGER.info("Skipped overwriting " + supportingFile.destinationFilename + " as the file already exists in " + folder); @@ -3613,6 +3610,9 @@ public void setParameterBooleanFlagWithCodegenProperty(CodegenParameter paramete } else if (Boolean.TRUE.equals(property.isByteArray)) { parameter.isByteArray = true; parameter.isPrimitiveType = true; + } else if (Boolean.TRUE.equals(property.isBinary)) { + parameter.isByteArray = true; + parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isString)) { parameter.isString = true; parameter.isPrimitiveType = true; @@ -3631,14 +3631,9 @@ public void setParameterBooleanFlagWithCodegenProperty(CodegenParameter paramete } else if (Boolean.TRUE.equals(property.isFloat)) { parameter.isFloat = true; parameter.isPrimitiveType = true; - } else if (Boolean.TRUE.equals(property.isNumber)) { + } else if (Boolean.TRUE.equals(property.isNumber)) { parameter.isNumber = true; parameter.isPrimitiveType = true; - } else if (Boolean.TRUE.equals(property.isBinary)) { - parameter.isByteArray = true; - parameter.isPrimitiveType = true; - } else if (Boolean.TRUE.equals(property.isFile)) { - parameter.isFile = true; } else if (Boolean.TRUE.equals(property.isDate)) { parameter.isDate = true; parameter.isPrimitiveType = true; @@ -3648,6 +3643,10 @@ public void setParameterBooleanFlagWithCodegenProperty(CodegenParameter paramete } else { LOGGER.debug("Property type is not primitive: " + property.datatype); } + + if (Boolean.TRUE.equals(property.isFile)) { + parameter.isFile = true; + } } @@ -3659,7 +3658,7 @@ public void setParameterBooleanFlagWithCodegenProperty(CodegenParameter paramete public void updateCodegenPropertyEnum(CodegenProperty var) { Map allowableValues = var.allowableValues; - // handle ArrayProperty + // handle array if (var.items != null) { allowableValues = var.items.allowableValues; } @@ -3749,7 +3748,7 @@ public boolean convertPropertyToBooleanAndWriteBack(String propertyKey) { /** * Provides an override location, if any is specified, for the .swagger-codegen-ignore. - * + *

* This is originally intended for the first generation only. * * @return a string of the full path to an override ignore file. @@ -3779,4 +3778,552 @@ public boolean convertPropertyToBoolean(String propertyKey) { public void writePropertyBack(String propertyKey, boolean value) { additionalProperties.put(propertyKey, value); } + + protected String getContentType(RequestBody requestBody) { + if (requestBody == null || requestBody.getContent() == null || requestBody.getContent().isEmpty()) { + return null; + } + return new ArrayList<>(requestBody.getContent().keySet()).get(0); + } + + protected Schema getSchemaFromBody(RequestBody requestBody) { + String contentType = new ArrayList<>(requestBody.getContent().keySet()).get(0); + MediaType mediaType = requestBody.getContent().get(contentType); + return mediaType.getSchema(); + } + + protected Schema getSchemaFromResponse(ApiResponse response) { + if (response.getContent() == null || response.getContent().isEmpty()) { + return null; + } + Schema schema = null; + for (MediaType mediaType : response.getContent().values()) { + schema = mediaType.getSchema(); + break; + } + return schema; + } + + protected Parameter getParameterFromRef(String ref, OpenAPI openAPI) { + String parameterName = ref.substring(ref.lastIndexOf('/') + 1); + Map parameterMap = openAPI.getComponents().getParameters(); + return parameterMap.get(parameterName); + } + + private void setOauth2Info(CodegenSecurity codegenSecurity, OAuthFlow flow) { + codegenSecurity.authorizationUrl = flow.getAuthorizationUrl(); + codegenSecurity.tokenUrl = flow.getTokenUrl(); + + if (flow.getScopes() != null && !flow.getScopes().isEmpty()) { + List> scopes = new ArrayList>(); + int count = 0, numScopes = flow.getScopes().size(); + for (Map.Entry scopeEntry : flow.getScopes().entrySet()) { + Map scope = new HashMap(); + scope.put("scope", scopeEntry.getKey()); + scope.put("description", escapeText(scopeEntry.getValue())); + + count += 1; + if (count < numScopes) { + scope.put("hasMore", "true"); + } else { + scope.put("hasMore", null); + } + + scopes.add(scope); + } + codegenSecurity.scopes = scopes; + } + } + + private List getInterfaces(ComposedSchema composed) { + List interfaces; + if (composed.getAllOf() != null && !composed.getAllOf().isEmpty()) { + return composed.getAllOf(); + } else if (composed.getAnyOf() != null && !composed.getAnyOf().isEmpty()) { + return composed.getAnyOf(); + } else if (composed.getOneOf() != null && !composed.getOneOf().isEmpty()) { + return composed.getOneOf(); + } else { + return null; + } + } + + private void addConsumesInfo(Operation operation, CodegenOperation codegenOperation) { + if (operation.getRequestBody() == null || operation.getRequestBody().getContent() == null || operation.getRequestBody().getContent().isEmpty()) { + return; + } + + Set consumes = operation.getRequestBody().getContent().keySet(); + List> mediaTypeList = new ArrayList<>(); + int count = 0; + for (String key : consumes) { + Map mediaType = new HashMap<>(); + if ("*/*".equals(key)) { + // skip as it implies `consumes` in OAS2 is not defined + continue; + } else { + mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); + } + + count += 1; + if (count < consumes.size()) { + mediaType.put("hasMore", "true"); + } else { + mediaType.put("hasMore", null); + } + + mediaTypeList.add(mediaType); + } + + if (!mediaTypeList.isEmpty()) { + codegenOperation.consumes = mediaTypeList; + codegenOperation.hasConsumes = true; + } + } + + public static Set getConsumesInfo(Operation operation) { + if (operation.getRequestBody() == null || operation.getRequestBody().getContent() == null || operation.getRequestBody().getContent().isEmpty()) { + return Collections.emptySet(); // return emtpy set + } + return operation.getRequestBody().getContent().keySet(); + } + + public Boolean hasFormParameter(Operation operation) { + Set consumesInfo = getConsumesInfo(operation); + + if (consumesInfo == null || consumesInfo.isEmpty()) { + return Boolean.FALSE; + } + + List consumes = new ArrayList(consumesInfo); + + if (consumes == null) { + return Boolean.FALSE; + } + + for (String consume : consumes) { + if ("application/x-www-form-urlencoded".equalsIgnoreCase(consume) || "multipart/form-data".equalsIgnoreCase(consume)) { + return Boolean.TRUE; + } + } + + return Boolean.FALSE; + } + + public Boolean hasBodyParameter(Operation operation) { + RequestBody requestBody = operation.getRequestBody(); + if (requestBody == null) { + return Boolean.FALSE; + } + + Schema schema = getSchemaFromBody(requestBody); + if (schema == null) { + return Boolean.FALSE; + } + + if (!StringUtils.isEmpty(schema.get$ref())) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + private void addProducesInfo(ApiResponse response, CodegenOperation codegenOperation) { + if (response == null || response.getContent() == null || response.getContent().isEmpty()) { + return; + } + + Set produces = response.getContent().keySet(); + if (codegenOperation.produces == null) { + codegenOperation.produces = new ArrayList<>(); + } + + int count = 0; + for (String key : produces) { + Map mediaType = new HashMap(); + // escape quotation to avoid code injection + if ("*/*".equals(key)) { // "*/*" is a special case, do nothing + mediaType.put("mediaType", key); + } else { + mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); + } + + count += 1; + if (count < produces.size()) { + mediaType.put("hasMore", "true"); + } else { + mediaType.put("hasMore", null); + } + + codegenOperation.produces.add(mediaType); + codegenOperation.hasProduces = Boolean.TRUE; + } + } + + /** + * returns the list of MIME types the APIs can produce + * + * @param operation Operation + * @return a set of MIME types + */ + public static Set getProducesInfo(Operation operation) { + if (operation.getResponses() == null || operation.getResponses().isEmpty()) { + return null; + } + + Set produces = new TreeSet(); + + for (ApiResponse response : operation.getResponses().values()) { + if (response.getContent() != null) { + produces.addAll(response.getContent().keySet()); + } + } + + return produces; + } + + protected Schema detectParent(ComposedSchema composedSchema, Map allSchemas) { + if (composedSchema.getAllOf() != null && !composedSchema.getAllOf().isEmpty()) { + Schema schema = composedSchema.getAllOf().get(0); + String ref = schema.get$ref(); + if (StringUtils.isBlank(ref)) { + return null; + } + ref = getSimpleRef(ref); + return allSchemas.get(ref); + } + return null; + } + + protected String getParentName(ComposedSchema composedSchema, Map allSchemas) { + if (composedSchema.getAllOf() != null && !composedSchema.getAllOf().isEmpty()) { + Schema schema = composedSchema.getAllOf().get(0); + String ref = schema.get$ref(); + if (StringUtils.isBlank(ref)) { + return null; + } + return getSimpleRef(ref); + } + return null; + } + + protected String getSimpleRef(String ref) { + if (ref.startsWith("#/components/")) { + ref = ref.substring(ref.lastIndexOf("/") + 1); + } else if (ref.startsWith("#/definitions/")) { + ref = ref.substring(ref.lastIndexOf("/") + 1); + } + + return ref; + } + + protected String getCollectionFormat(Parameter parameter) { + if (Parameter.StyleEnum.FORM.equals(parameter.getStyle())) { + // Ref: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#style-values + if (Boolean.TRUE.equals(parameter.getExplode())) { // explode is true (default) + return "multi"; + } else { + return "csv"; + } + } else if (Parameter.StyleEnum.SIMPLE.equals(parameter.getStyle())) { + return "csv"; + } else if (Parameter.StyleEnum.PIPEDELIMITED.equals(parameter.getStyle())) { + return "pipe"; + } else if (Parameter.StyleEnum.SPACEDELIMITED.equals(parameter.getStyle())) { + return "space"; + } else { + return null; + } + } + + // TODO do we still need the methdo below? + protected static boolean hasSchemaProperties(Schema schema) { + final Object additionalProperties = schema.getAdditionalProperties(); + return additionalProperties != null && additionalProperties instanceof Schema; + } + + public CodegenType getTag() { + return null; + } + + public String getName() { + return null; + } + + public String getHelp() { + return null; + } + + public List fromRequestBodyToFormParameters(RequestBody body, Map schemas, Set imports) { + List parameters = new ArrayList(); + LOGGER.debug("debugging fromRequestBodyToFormParameters= " + body); + Schema schema = getSchemaFromBody(body); + if (StringUtils.isNotBlank(schema.get$ref())) { + schema = schemas.get(getSimpleRef(schema.get$ref())); + } + if (schema.getProperties() != null && !schema.getProperties().isEmpty()) { + Map properties = schema.getProperties(); + for (Map.Entry entry : properties.entrySet()) { + CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); + // key => property anme + // value => property schema + codegenParameter = fromFormProperty(entry.getKey(), entry.getValue(), imports); + + // Set 'required' flag defined in the schema element + if (!codegenParameter.required && schema.getRequired() != null) { + codegenParameter.required = schema.getRequired().contains(entry.getKey()); + } + + parameters.add(codegenParameter); + } + } + + return parameters; + } + + public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set imports) { + CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); + + LOGGER.debug("Debugging fromFormProperty: " + name); + CodegenProperty codegenProperty = fromProperty(name, propertySchema); + + codegenParameter.isFormParam = Boolean.TRUE; + codegenParameter.baseName = codegenProperty.baseName; + codegenParameter.paramName = toParamName((codegenParameter.baseName)); + codegenParameter.baseType = codegenProperty.baseType; + codegenParameter.dataType = codegenProperty.datatype; + codegenParameter.dataFormat = codegenProperty.dataFormat; + codegenParameter.description = escapeText(codegenProperty.description); + codegenParameter.unescapedDescription = codegenProperty.getDescription(); + codegenParameter.jsonSchema = Json.pretty(propertySchema); + + + if (codegenProperty.getVendorExtensions() != null && !codegenProperty.getVendorExtensions().isEmpty()) { + codegenParameter.vendorExtensions = codegenProperty.getVendorExtensions(); + } + if (propertySchema.getRequired() != null && !propertySchema.getRequired().isEmpty() && propertySchema.getRequired().contains(codegenProperty.baseName)) { + codegenParameter.required = Boolean.TRUE; + } + + // non-array/map + updateCodegenPropertyEnum(codegenProperty); + codegenParameter.isEnum = codegenProperty.isEnum; + codegenParameter._enum = codegenProperty._enum; + codegenParameter.allowableValues = codegenProperty.allowableValues; + + if (codegenProperty.items != null && codegenProperty.items.isEnum) { + codegenParameter.datatypeWithEnum = codegenProperty.datatypeWithEnum; + codegenParameter.enumName = codegenProperty.enumName; + codegenParameter.items = codegenProperty.items; + } + + // import + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); + } + + // validation + // handle maximum, minimum properly for int/long by removing the trailing ".0" + if (ModelUtils.isIntegerSchema(propertySchema)) { + codegenParameter.maximum = propertySchema.getMaximum() == null ? null : String.valueOf(propertySchema.getMaximum().longValue()); + codegenParameter.minimum = propertySchema.getMinimum() == null ? null : String.valueOf(propertySchema.getMinimum().longValue()); + } else { + codegenParameter.maximum = propertySchema.getMaximum() == null ? null : String.valueOf(propertySchema.getMaximum()); + codegenParameter.minimum = propertySchema.getMinimum() == null ? null : String.valueOf(propertySchema.getMinimum()); + } + + codegenParameter.exclusiveMaximum = propertySchema.getExclusiveMaximum() == null ? false : propertySchema.getExclusiveMaximum(); + codegenParameter.exclusiveMinimum = propertySchema.getExclusiveMinimum() == null ? false : propertySchema.getExclusiveMinimum(); + codegenParameter.maxLength = propertySchema.getMaxLength(); + codegenParameter.minLength = propertySchema.getMinLength(); + codegenParameter.pattern = toRegularExpression(propertySchema.getPattern()); + codegenParameter.maxItems = propertySchema.getMaxItems(); + codegenParameter.minItems = propertySchema.getMinItems(); + codegenParameter.uniqueItems = propertySchema.getUniqueItems() == null ? false : propertySchema.getUniqueItems(); + codegenParameter.multipleOf = propertySchema.getMultipleOf(); + + // exclusive* are noop without corresponding min/max + if (codegenParameter.maximum != null || codegenParameter.minimum != null || + codegenParameter.maxLength != null || codegenParameter.minLength != null || + codegenParameter.maxItems != null || codegenParameter.minItems != null || + codegenParameter.pattern != null) { + codegenParameter.hasValidation = true; + } + + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + setParameterExampleValue(codegenParameter); + + //TODO collectionFormat for form parameter not yet supported + //codegenParameter.collectionFormat = getCollectionFormat(propertySchema); + return codegenParameter; + } + + public CodegenParameter fromRequestBody(RequestBody body, Map schemas, Set imports) { + if (body == null) { + LOGGER.error("body in fromRequestBody cannot be null!"); + } + CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); + codegenParameter.baseName = "UNKNOWN_BASE_NAME"; + codegenParameter.paramName = "UNKNOWN_PARAM_NAME"; + codegenParameter.required = body.getRequired() != null ? body.getRequired() : Boolean.FALSE; + codegenParameter.isBodyParam = Boolean.TRUE; + + String name = null; + LOGGER.debug("Request body = " + body); + Schema schema = getSchemaFromBody(body); + if (StringUtils.isNotBlank(schema.get$ref())) { + name = getSimpleRef(schema.get$ref()); + schema = schemas.get(name); + } + + if (ModelUtils.isObjectSchema(schema)) { + CodegenModel codegenModel = null; + if (StringUtils.isNotBlank(name)) { + schema.setName(name); + codegenModel = fromModel(name, schema, schemas); + } + if (codegenModel != null && !codegenModel.emptyVars) { + codegenParameter.baseName = codegenModel.classname; + codegenParameter.paramName = toParamName(codegenModel.classname); + codegenParameter.baseType = codegenModel.classname; + codegenParameter.dataType = codegenModel.classname; + codegenParameter.description = codegenModel.description; + imports.add(codegenParameter.baseType); + } else { + CodegenProperty codegenProperty = fromProperty("property", schema); + if (codegenProperty != null) { + LOGGER.warn("The folowing schema has undefined (null) baseType. " + + "It could be due to form parameter defined in OpenAPI v2 spec with incorrect consumes. " + + "A correct 'consumes' for form parameters should be " + + "'application/x-www-form-urlencoded' or 'multipart/form-data'"); + LOGGER.warn("schema: " + schema); + LOGGER.warn("Defaulting baseType to UNKNOWN_BASE_TYPE"); + codegenProperty.baseType = "UNKNOWN_BASE_TYPE"; + + codegenParameter.baseName = codegenProperty.baseType; + codegenParameter.baseType = codegenProperty.baseType; + codegenParameter.dataType = codegenProperty.datatype; + codegenParameter.description = codegenProperty.description; + codegenParameter.paramName = toParamName(codegenProperty.baseType); + + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); + } + } + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + } + } else if (ModelUtils.isArraySchema(schema)) { + final ArraySchema arraySchema = (ArraySchema) schema; + Schema inner = arraySchema.getItems(); + if (inner == null) { + inner = new StringSchema().description("//TODO automatically added by swagger-codegen"); + arraySchema.setItems(inner); + } + CodegenProperty codegenProperty = fromProperty("inner", inner); + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); + } + imports.add(codegenProperty.baseType); + CodegenProperty innerCp = codegenProperty; + while (innerCp != null) { + if (innerCp.complexType != null) { + imports.add(innerCp.complexType); + } + innerCp = innerCp.items; + } + codegenParameter.baseName = codegenProperty.baseType; + codegenParameter.paramName = toParamName(codegenProperty.baseType); + codegenParameter.items = codegenProperty; + codegenParameter.dataType = getTypeDeclaration(arraySchema); + codegenParameter.baseType = codegenProperty.complexType; + codegenParameter.isContainer = Boolean.TRUE; + codegenParameter.isListContainer = Boolean.TRUE; + codegenParameter.description = codegenProperty.description; + + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + + while (codegenProperty != null) { + imports.add(codegenProperty.baseType); + codegenProperty = codegenProperty.items; + } + } else { + // HTTP request body is primitive type (e.g. integer, string, etc) + CodegenProperty codegenProperty = fromProperty("PRIMITIVE_REQUEST_BODY", schema); + if (codegenProperty != null) { + if (schema.getExtensions() != null && schema.getExtensions().containsKey("x-codegen-body-parameter-name")) { + codegenParameter.baseName = (String) schema.getExtensions().get("x-codegen-body-parameter-name"); + } else { + codegenParameter.baseName = "body"; // default to body + } + codegenParameter.isPrimitiveType = true; + codegenParameter.baseType = codegenProperty.baseType; + codegenParameter.dataType = codegenProperty.datatype; + codegenParameter.description = codegenProperty.description; + codegenParameter.paramName = toParamName(codegenParameter.baseName); + + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); + } + + } + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + } + + // set the parameter's example value + // should be overridden by lang codegen + setParameterExampleValue(codegenParameter); + + return codegenParameter; + } + + protected void addOption(String key, String description) { + addOption(key, description, null); + } + + protected void addOption(String key, String description, String defaultValue) { + CliOption option = new CliOption(key, description); + if (defaultValue != null) + option.defaultValue(defaultValue); + cliOptions.add(option); + } + + protected void addSwitch(String key, String description, Boolean defaultValue) { + CliOption option = CliOption.newBoolean(key, description); + if (defaultValue != null) + option.defaultValue(defaultValue.toString()); + cliOptions.add(option); + } + + /** + * generates OpenAPI specification file in JSON format + * + * @param objs map of object + */ + public void generateJSONSpecFile(Map objs) { + OpenAPI openAPI = (OpenAPI) objs.get("openAPI"); + if (openAPI != null) { + try { + objs.put("openapi-json", Json.pretty().writeValueAsString(openAPI).replace("\r\n", "\n")); + } catch (JsonProcessingException e) { + LOGGER.error(e.getMessage(), e); + } + } + } + + /** + * generates OpenAPI specification file in YAML format + * + * @param objs map of object + */ + public void generateYAMLSpecFile(Map objs) { + OpenAPI openAPI = (OpenAPI) objs.get("openAPI"); + if (openAPI != null) { + try { + objs.put("openapi-yaml", Yaml.mapper().writeValueAsString(openAPI)); + } catch (JsonProcessingException e) { + LOGGER.error(e.getMessage(), e); + } + } + } + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java index 4019ff22b141..8a0b45c2cbbe 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java @@ -2,29 +2,42 @@ import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; -import org.openapitools.codegen.ignore.CodegenIgnoreProcessor; -import org.openapitools.codegen.languages.AbstractJavaCodegen; -import org.openapitools.codegen.utils.ImplementationVersion; -import io.swagger.models.*; -import io.swagger.models.auth.OAuth2Definition; -import io.swagger.models.auth.SecuritySchemeDefinition; -import io.swagger.models.parameters.Parameter; -import io.swagger.util.Json; + +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.PathItem; +import io.swagger.v3.oas.models.Paths; +import io.swagger.v3.oas.models.info.Contact; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.info.License; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.tags.Tag; + import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; +import org.openapitools.codegen.ignore.CodegenIgnoreProcessor; +//import org.openapitools.codegen.languages.AbstractJavaCodegen; +import org.openapitools.codegen.utils.ImplementationVersion; +import org.openapitools.codegen.utils.ModelUtils; +import org.openapitools.codegen.utils.URLPathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*; +import java.net.*; public class DefaultGenerator extends AbstractGenerator implements Generator { protected final Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class); protected CodegenConfig config; protected ClientOptInput opts; - protected Swagger swagger; + protected OpenAPI openAPI; protected CodegenIgnoreProcessor ignoreProcessor; private Boolean generateApis = null; private Boolean generateModels = null; @@ -42,7 +55,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { @Override public Generator opts(ClientOptInput opts) { this.opts = opts; - this.swagger = opts.getSwagger(); + this.openAPI= opts.getOpenAPI(); this.config = opts.getConfig(); this.config.additionalProperties().putAll(opts.getOpts().getProperties()); @@ -95,33 +108,6 @@ private Boolean getGeneratorPropertyDefaultSwitch(final String key, final Boolea return defaultValue; } - private String getScheme() { - String scheme; - if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { - scheme = config.escapeText(swagger.getSchemes().get(0).toValue()); - } else { - scheme = "https"; - } - scheme = config.escapeText(scheme); - return scheme; - } - - private String getHost() { - StringBuilder hostBuilder = new StringBuilder(); - hostBuilder.append(getScheme()); - hostBuilder.append("://"); - if (!StringUtils.isEmpty(swagger.getHost())) { - hostBuilder.append(swagger.getHost()); - } else { - hostBuilder.append("localhost"); - LOGGER.warn("'host' not defined in the spec. Default to 'localhost'."); - } - if (!StringUtils.isEmpty(swagger.getBasePath()) && !swagger.getBasePath().equals("/")) { - hostBuilder.append(swagger.getBasePath()); - } - return hostBuilder.toString(); - } - private void configureGeneratorProperties() { // allows generating only models by specifying a CSV of models to generate, or empty for all // NOTE: Boolean.TRUE is required below rather than `true` because of JVM boxing constraints and type inference. @@ -164,28 +150,36 @@ private void configureGeneratorProperties() { if (!generateApiTests && !generateModelTests) { config.additionalProperties().put(CodegenConstants.EXCLUDE_TESTS, true); } + // for backward compatibility if (System.getProperty("debugSwagger") != null) { - Json.prettyPrint(swagger); + LOGGER.info("Please use 'debugOpenAPI' instead of 'debugSwagger` moving forward."); + Json.prettyPrint(openAPI); + } + + if (System.getProperty("debugOpenAPI") != null) { + Json.prettyPrint(openAPI); } + config.processOpts(); - config.preprocessSwagger(swagger); + config.preprocessOpenAPI(openAPI); config.additionalProperties().put("generatorVersion", ImplementationVersion.read()); config.additionalProperties().put("generatedDate", DateTime.now().toString()); config.additionalProperties().put("generatedYear", String.valueOf(DateTime.now().getYear())); config.additionalProperties().put("generatorClass", config.getClass().getName()); config.additionalProperties().put("inputSpec", config.getInputSpec()); - if (swagger.getVendorExtensions() != null) { - config.vendorExtensions().putAll(swagger.getVendorExtensions()); - } - contextPath = config.escapeText(swagger.getBasePath() == null ? "" : swagger.getBasePath()); - basePath = config.escapeText(getHost()); - basePathWithoutHost = config.escapeText(swagger.getBasePath()); + if (openAPI.getExtensions() != null) { + config.vendorExtensions().putAll(openAPI.getExtensions()); + } + URL url = URLPathUtils.getServerURL(openAPI); + contextPath = config.escapeText(url == null ? "" : url.getPath()); + basePath = config.escapeText(URLPathUtils.getHost(openAPI)); + basePathWithoutHost = contextPath; // for backward compatibility } - private void configureSwaggerInfo() { - Info info = swagger.getInfo(); + private void configureOpenAPIInfo() { + Info info = this.openAPI.getInfo(); if (info == null) { return; } @@ -276,14 +270,13 @@ private void generateModelDocumentation(List files, Map mo } } - private void generateModels(List files, List allModels) { - + private void generateModels(List files, List allModels, List unusedModels) { if (!generateModels) { return; } - final Map definitions = swagger.getDefinitions(); - if (definitions == null) { + final Map schemas = this.openAPI.getComponents().getSchemas(); + if (schemas == null) { return; } @@ -293,7 +286,7 @@ private void generateModels(List files, List allModels) { modelsToGenerate = new HashSet(Arrays.asList(modelNames.split(","))); } - Set modelKeys = definitions.keySet(); + Set modelKeys = schemas.keySet(); if (modelsToGenerate != null && !modelsToGenerate.isEmpty()) { Set updatedKeys = new HashSet(); for (String m : modelKeys) { @@ -301,6 +294,7 @@ private void generateModels(List files, List allModels) { updatedKeys.add(m); } } + modelKeys = updatedKeys; } @@ -308,6 +302,10 @@ private void generateModels(List files, List allModels) { Map allProcessedModels = new TreeMap(new Comparator() { @Override public int compare(String o1, String o2) { + return ObjectUtils.compare(config.toModelName(o1), config.toModelName(o2)); + } + /* TODO need to revise the logic below + Model model1 = definitions.get(o1); Model model2 = definitions.get(o2); @@ -352,7 +350,7 @@ private Model getParent(Model model) { } return null; - } + } */ }); // process models only @@ -360,13 +358,20 @@ private Model getParent(Model model) { try { //don't generate models that have an import mapping if (config.importMapping().containsKey(name)) { - LOGGER.info("Model " + name + " not imported due to import mapping"); + LOGGER.debug("Model " + name + " not imported due to import mapping"); continue; } - Model model = definitions.get(name); - Map modelMap = new HashMap(); - modelMap.put(name, model); - Map models = processModels(config, modelMap, definitions); + + // don't generate models that are not used as object (e.g. form parameters) + if (unusedModels.contains(name)) { + LOGGER.debug("Model " + name + " not generated since it's marked as unused (due to form parameters)"); + continue; + } + + Schema schema = schemas.get(name); + Map schemaMap = new HashMap<>(); + schemaMap.put(name, schema); + Map models = processModels(config, schemaMap, schemas); models.put("classname", config.toModelName(name)); models.putAll(config.additionalProperties()); allProcessedModels.put(name, models); @@ -388,6 +393,7 @@ private Model getParent(Model model) { continue; } Map modelTemplate = (Map) ((List) models.get("models")).get(0); + /* TODO revise alias handling if (config instanceof AbstractJavaCodegen) { // Special handling of aliases only applies to Java if (modelTemplate != null && modelTemplate.containsKey("model")) { @@ -396,8 +402,10 @@ private Model getParent(Model model) { continue; // Don't create user-defined classes for aliases } } - } + }*/ + allModels.add(modelTemplate); + for (String templateName : config.modelTemplateFiles().keySet()) { String suffix = config.modelTemplateFiles().get(templateName); String filename = config.modelFileFolder() + File.separator + config.toModelFilename(modelName) + suffix; @@ -432,7 +440,7 @@ private void generateApis(List files, List allOperations, List> paths = processPaths(swagger.getPaths()); + Map> paths = processPaths(this.openAPI.getPaths()); Set apisToGenerate = null; String apiNames = System.getProperty("apis"); if (apiNames != null && !apiNames.isEmpty()) { @@ -481,8 +489,10 @@ public int compare(CodegenOperation one, CodegenOperation another) { } operation.put("sortParamsByRequiredFlag", sortParamsByRequiredFlag); + /* consumes, produces are no longer defined in OAS3.0 processMimeTypes(swagger.getConsumes(), operation, "consumes"); processMimeTypes(swagger.getProduces(), operation, "produces"); + */ allOperations.add(new HashMap(operation)); for (int i = 0; i < allOperations.size(); i++) { @@ -692,27 +702,33 @@ private Map buildSupportFileBundle(List allOperations, L Map apis = new HashMap(); apis.put("apis", allOperations); - if (swagger.getHost() != null) { - bundle.put("host", swagger.getHost()); + URL url = URLPathUtils.getServerURL(openAPI); + if (url != null) { + bundle.put("host", url.getHost()); } - bundle.put("swagger", this.swagger); + bundle.put("openAPI", openAPI); + bundle.put("swagger", openAPI); // for backward compatibility bundle.put("basePath", basePath); bundle.put("basePathWithoutHost", basePathWithoutHost); - bundle.put("scheme", getScheme()); + bundle.put("scheme", URLPathUtils.getScheme(openAPI, config)); bundle.put("contextPath", contextPath); bundle.put("apiInfo", apis); bundle.put("models", allModels); bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar)); bundle.put("modelPackage", config.modelPackage()); - List authMethods = config.fromSecurity(swagger.getSecurityDefinitions()); + + Map securitySchemeMap = openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null; + List authMethods = config.fromSecurity(securitySchemeMap); if (authMethods != null && !authMethods.isEmpty()) { bundle.put("authMethods", authMethods); bundle.put("hasAuthMethods", true); } - if (swagger.getExternalDocs() != null) { - bundle.put("externalDocs", swagger.getExternalDocs()); + + if (openAPI.getExternalDocs() != null) { + bundle.put("externalDocs", openAPI.getExternalDocs()); } + for (int i = 0; i < allModels.size() - 1; i++) { HashMap cm = (HashMap) allModels.get(i); CodegenModel m = cm.get("model"); @@ -731,20 +747,26 @@ private Map buildSupportFileBundle(List allOperations, L @Override public List generate() { - if (swagger == null || config == null) { - throw new RuntimeException("missing swagger input or config!"); + if (openAPI == null) { + throw new RuntimeException("missing OpenAPI input!"); + } + + if (config == null) { + throw new RuntimeException("missing config!"); } + configureGeneratorProperties(); - configureSwaggerInfo(); + configureOpenAPIInfo(); // resolve inline models - InlineModelResolver inlineModelResolver = new InlineModelResolver(); - inlineModelResolver.flatten(swagger); + //InlineModelResolver inlineModelResolver = new InlineModelResolver(); + //inlineModelResolver.flatten(openAPI); List files = new ArrayList(); // models + List unusedSchemas = ModelUtils.getUnusedSchemas(openAPI); List allModels = new ArrayList(); - generateModels(files, allModels); + generateModels(files, allModels, unusedSchemas); // apis List allOperations = new ArrayList(); generateApis(files, allOperations, allModels); @@ -752,7 +774,7 @@ public List generate() { // supporting files Map bundle = buildSupportFileBundle(allOperations, allModels); generateSupportingFiles(files, bundle); - config.processSwagger(swagger); + config.processOpenAPI(openAPI); return files; } @@ -782,33 +804,10 @@ public Reader getTemplate(String name) { return null; } - private static void processMimeTypes(List mimeTypeList, Map operation, String source) { - if (mimeTypeList == null || mimeTypeList.isEmpty()) { - return; - } - List> c = new ArrayList>(); - int count = 0; - for (String key : mimeTypeList) { - Map mediaType = new HashMap(); - mediaType.put("mediaType", key); - count += 1; - if (count < mimeTypeList.size()) { - mediaType.put("hasMore", "true"); - } else { - mediaType.put("hasMore", null); - } - c.add(mediaType); - } - operation.put(source, c); - String flagFieldName = "has" + source.substring(0, 1).toUpperCase() + source.substring(1); - operation.put(flagFieldName, true); - - } - - public Map> processPaths(Map paths) { + public Map> processPaths(Paths paths) { Map> ops = new TreeMap>(); for (String resourcePath : paths.keySet()) { - Path path = paths.get(resourcePath); + PathItem path = paths.get(resourcePath); processOperation(resourcePath, "get", path.getGet(), ops, path); processOperation(resourcePath, "head", path.getHead(), ops, path); processOperation(resourcePath, "put", path.getPut(), ops, path); @@ -820,17 +819,18 @@ public Map> processPaths(Map paths) return ops; } - private void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations, Path path) { + private void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations, PathItem path) { if (operation == null) { return; } + if (System.getProperty("debugOperations") != null) { LOGGER.info("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + " " + operation + "\n"); } - List tags = new ArrayList(); + List tags = new ArrayList(); List tagNames = operation.getTags(); - List swaggerTags = swagger.getTags(); + List swaggerTags = openAPI.getTags(); if (tagNames != null) { if (swaggerTags == null) { for (String tagName : tagNames) { @@ -874,64 +874,48 @@ private void processOperation(String resourcePath, String httpMethod, Operation if (path.getParameters() != null) { for (Parameter parameter : path.getParameters()) { //skip propagation if a parameter with the same name is already defined at the operation level - if (!operationParameters.contains(generateParameterId(parameter))) { - operation.addParameter(parameter); + if (!operationParameters.contains(generateParameterId(parameter)) && operation.getParameters() != null) { + operation.getParameters().add(parameter); } } } + final Map schemas = openAPI.getComponents() != null ? openAPI.getComponents().getSchemas() : null; + final Map securitySchemes = openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null; + final List globalSecurities = openAPI.getSecurity(); for (Tag tag : tags) { try { - CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger); - codegenOperation.tags = new ArrayList(tags); + CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, schemas, openAPI); + codegenOperation.tags = new ArrayList<>(tags); config.addOperationToGroup(config.sanitizeTag(tag.getName()), resourcePath, operation, codegenOperation, operations); - List>> securities = operation.getSecurity(); - if (securities == null && swagger.getSecurity() != null) { - securities = new ArrayList>>(); - for (SecurityRequirement sr : swagger.getSecurity()) { - securities.add(sr.getRequirements()); - } - } - if (securities == null || swagger.getSecurityDefinitions() == null) { + List securities = operation.getSecurity(); + if (securities != null && securities.isEmpty()) { continue; } - Map authMethods = new HashMap(); - for (Map> security : securities) { - for (String securityName : security.keySet()) { - SecuritySchemeDefinition securityDefinition = swagger.getSecurityDefinitions().get(securityName); - if (securityDefinition == null) { - continue; - } - if (securityDefinition instanceof OAuth2Definition) { - OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition; - OAuth2Definition oauth2Operation = new OAuth2Definition(); - oauth2Operation.setType(oauth2Definition.getType()); - oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl()); - oauth2Operation.setFlow(oauth2Definition.getFlow()); - oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl()); - oauth2Operation.setScopes(new HashMap()); - for (String scope : security.get(securityName)) { - if (oauth2Definition.getScopes().containsKey(scope)) { - oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope)); - } - } - authMethods.put(securityName, oauth2Operation); - } else { - authMethods.put(securityName, securityDefinition); - } - } + Map authMethods = getAuthMethods(securities, securitySchemes); + if (authMethods == null || authMethods.isEmpty()) { + authMethods = getAuthMethods(globalSecurities, securitySchemes); } - if (!authMethods.isEmpty()) { + + if (authMethods != null && !authMethods.isEmpty()) { codegenOperation.authMethods = config.fromSecurity(authMethods); codegenOperation.hasAuthMethods = true; } + + /* TODO need to revise the logic below + Map securitySchemeMap = openAPI.getComponents().getSecuritySchemes(); + if (securitySchemeMap != null && !securitySchemeMap.isEmpty()) { + codegenOperation.authMethods = config.fromSecurity(securitySchemeMap); + codegenOperation.hasAuthMethods = true; + } + */ } catch (Exception ex) { String msg = "Could not process operation:\n" // + " Tag: " + tag + "\n"// + " Operation: " + operation.getOperationId() + "\n" // + " Resource: " + httpMethod + " " + resourcePath + "\n"// - + " Definitions: " + swagger.getDefinitions() + "\n" // + + " Schemas: " + openAPI.getComponents().getSchemas() + "\n" // + " Exception: " + ex.getMessage(); throw new RuntimeException(msg, ex); } @@ -966,7 +950,6 @@ private Map processOperations(CodegenConfig config, String tag, operations.put("operations", objs); operations.put("package", config.apiPackage()); - Set allImports = new TreeSet(); for (CodegenOperation op : ops) { allImports.addAll(op.imports); @@ -1007,14 +990,16 @@ private Map processOperations(CodegenConfig config, String tag, } - private Map processModels(CodegenConfig config, Map definitions, Map allDefinitions) { + private Map processModels(CodegenConfig config, Map definitions, Map allDefinitions) { Map objs = new HashMap(); objs.put("package", config.modelPackage()); List models = new ArrayList(); Set allImports = new LinkedHashSet(); for (String key : definitions.keySet()) { - Model mm = definitions.get(key); - CodegenModel cm = config.fromModel(key, mm, allDefinitions); + Schema schema = definitions.get(key); + if (schema == null) + throw new RuntimeException("schema cannnot be null in processMoels"); + CodegenModel cm = config.fromModel(key, schema, allDefinitions); Map mo = new HashMap(); mo.put("model", cm); mo.put("importPath", config.toModelImport(cm.classname)); @@ -1048,4 +1033,20 @@ private Map processModels(CodegenConfig config, Map getAuthMethods(List securities, Map securitySchemes) { + if (securities == null || (securitySchemes == null || securitySchemes.isEmpty())) { + return null; + } + final Map authMethods = new HashMap<>(); + for (SecurityRequirement requirement : securities) { + for (String key : requirement.keySet()) { + SecurityScheme securityScheme = securitySchemes.get(key); + if (securityScheme != null) { + authMethods.put(key, securityScheme); + } + } + } + return authMethods; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java deleted file mode 100644 index cb97312d1d5f..000000000000 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java +++ /dev/null @@ -1,466 +0,0 @@ -package org.openapitools.codegen; - -import io.swagger.models.*; -import io.swagger.models.parameters.BodyParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.*; -import io.swagger.util.Json; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class InlineModelResolver { - private Swagger swagger; - private boolean skipMatches; - static Logger LOGGER = LoggerFactory.getLogger(InlineModelResolver.class); - - Map addedModels = new HashMap(); - Map generatedSignature = new HashMap(); - - public void flatten(Swagger swagger) { - this.swagger = swagger; - - if (swagger.getDefinitions() == null) { - swagger.setDefinitions(new HashMap()); - } - - // operations - Map paths = swagger.getPaths(); - Map models = swagger.getDefinitions(); - - if (paths != null) { - for (String pathname : paths.keySet()) { - Path path = paths.get(pathname); - - for (Operation operation : path.getOperations()) { - List parameters = operation.getParameters(); - - if (parameters != null) { - for (Parameter parameter : parameters) { - if (parameter instanceof BodyParameter) { - BodyParameter bp = (BodyParameter) parameter; - if (bp.getSchema() != null) { - Model model = bp.getSchema(); - if (model instanceof ModelImpl) { - ModelImpl obj = (ModelImpl) model; - if (obj.getType() == null || "object".equals(obj.getType())) { - if (obj.getProperties() != null && obj.getProperties().size() > 0) { - flattenProperties(obj.getProperties(), pathname); - String modelName = resolveModelName(obj.getTitle(), bp.getName()); - bp.setSchema(new RefModel(modelName)); - addGenerated(modelName, model); - swagger.addDefinition(modelName, model); - } - } - } else if (model instanceof ArrayModel) { - ArrayModel am = (ArrayModel) model; - Property inner = am.getItems(); - - if (inner instanceof ObjectProperty) { - ObjectProperty op = (ObjectProperty) inner; - if (op.getProperties() != null && op.getProperties().size() > 0) { - flattenProperties(op.getProperties(), pathname); - String modelName = resolveModelName(op.getTitle(), bp.getName()); - Model innerModel = modelFromProperty(op, modelName); - String existing = matchGenerated(innerModel); - if (existing != null) { - RefProperty refProperty = new RefProperty(existing); - refProperty.setRequired(op.getRequired()); - am.setItems(refProperty); - } else { - RefProperty refProperty = new RefProperty(modelName); - refProperty.setRequired(op.getRequired()); - am.setItems(refProperty); - addGenerated(modelName, innerModel); - swagger.addDefinition(modelName, innerModel); - } - } - } - } - } - } - } - } - Map responses = operation.getResponses(); - if (responses != null) { - for (String key : responses.keySet()) { - Response response = responses.get(key); - if (response.getSchema() != null) { - Property property = response.getSchema(); - if (property instanceof ObjectProperty) { - ObjectProperty op = (ObjectProperty) property; - if (op.getProperties() != null && op.getProperties().size() > 0) { - String modelName = resolveModelName(op.getTitle(), "inline_response_" + key); - Model model = modelFromProperty(op, modelName); - String existing = matchGenerated(model); - if (existing != null) { - Property refProperty = this.makeRefProperty(existing, property); - refProperty.setRequired(op.getRequired()); - response.setSchema(refProperty); - } else { - Property refProperty = this.makeRefProperty(modelName, property); - refProperty.setRequired(op.getRequired()); - response.setSchema(refProperty); - addGenerated(modelName, model); - swagger.addDefinition(modelName, model); - } - } - } else if (property instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) property; - Property inner = ap.getItems(); - - if (inner instanceof ObjectProperty) { - ObjectProperty op = (ObjectProperty) inner; - if (op.getProperties() != null && op.getProperties().size() > 0) { - flattenProperties(op.getProperties(), pathname); - String modelName = resolveModelName(op.getTitle(), - "inline_response_" + key); - Model innerModel = modelFromProperty(op, modelName); - String existing = matchGenerated(innerModel); - if (existing != null) { - Property refProperty = this.makeRefProperty(existing, op); - refProperty.setRequired(op.getRequired()); - ap.setItems(refProperty); - } else { - Property refProperty = this.makeRefProperty(modelName, op); - refProperty.setRequired(op.getRequired()); - ap.setItems(refProperty); - addGenerated(modelName, innerModel); - swagger.addDefinition(modelName, innerModel); - } - } - } - } else if (property instanceof MapProperty) { - MapProperty mp = (MapProperty) property; - - Property innerProperty = mp.getAdditionalProperties(); - if (innerProperty instanceof ObjectProperty) { - ObjectProperty op = (ObjectProperty) innerProperty; - if (op.getProperties() != null && op.getProperties().size() > 0) { - flattenProperties(op.getProperties(), pathname); - String modelName = resolveModelName(op.getTitle(), - "inline_response_" + key); - Model innerModel = modelFromProperty(op, modelName); - String existing = matchGenerated(innerModel); - if (existing != null) { - RefProperty refProperty = new RefProperty(existing); - refProperty.setRequired(op.getRequired()); - mp.setAdditionalProperties(refProperty); - } else { - RefProperty refProperty = new RefProperty(modelName); - refProperty.setRequired(op.getRequired()); - mp.setAdditionalProperties(refProperty); - addGenerated(modelName, innerModel); - swagger.addDefinition(modelName, innerModel); - } - } - } - } - } - } - } - } - } - } - - // definitions - if (models != null) { - List modelNames = new ArrayList(models.keySet()); - for (String modelName : modelNames) { - Model model = models.get(modelName); - if (model instanceof ModelImpl) { - ModelImpl m = (ModelImpl) model; - - Map properties = m.getProperties(); - flattenProperties(properties, modelName); - fixStringModel(m); - } else if (model instanceof ArrayModel) { - ArrayModel m = (ArrayModel) model; - Property inner = m.getItems(); - if (inner instanceof ObjectProperty) { - ObjectProperty op = (ObjectProperty) inner; - if (op.getProperties() != null && op.getProperties().size() > 0) { - String innerModelName = resolveModelName(op.getTitle(), modelName + "_inner"); - Model innerModel = modelFromProperty(op, innerModelName); - String existing = matchGenerated(innerModel); - if (existing == null) { - swagger.addDefinition(innerModelName, innerModel); - addGenerated(innerModelName, innerModel); - RefProperty refProperty = new RefProperty(innerModelName); - refProperty.setRequired(op.getRequired()); - m.setItems(refProperty); - } else { - RefProperty refProperty = new RefProperty(existing); - refProperty.setRequired(op.getRequired()); - m.setItems(refProperty); - } - } - } - } else if (model instanceof ComposedModel) { - ComposedModel m = (ComposedModel) model; - if (m.getChild() != null) { - Map properties = m.getChild().getProperties(); - flattenProperties(properties, modelName); - } - } - } - } - } - - /** - * This function fix models that are string (mostly enum). Before this fix, the example - * would look something like that in the doc: "\"example from def\"" - * @param m Model implementation - */ - private void fixStringModel(ModelImpl m) { - if (m.getType() != null && m.getType().equals("string") && m.getExample() != null) { - String example = m.getExample().toString(); - if (example.substring(0, 1).equals("\"") && - example.substring(example.length() - 1).equals("\"")) { - m.setExample(example.substring(1, example.length() - 1)); - } - } - } - - private String resolveModelName(String title, String key) { - if (title == null) { - return uniqueName(key); - } else { - return uniqueName(title); - } - } - - public String matchGenerated(Model model) { - if (this.skipMatches) { - return null; - } - String json = Json.pretty(model); - if (generatedSignature.containsKey(json)) { - return generatedSignature.get(json); - } - return null; - } - - public void addGenerated(String name, Model model) { - generatedSignature.put(Json.pretty(model), name); - } - - public String uniqueName(String key) { - int count = 0; - boolean done = false; - key = key.replaceAll("[^a-z_\\.A-Z0-9 ]", ""); // FIXME: a parameter - // should not be - // assigned. Also declare - // the methods parameters - // as 'final'. - while (!done) { - String name = key; - if (count > 0) { - name = key + "_" + count; - } - if (swagger.getDefinitions() == null) { - return name; - } else if (!swagger.getDefinitions().containsKey(name)) { - return name; - } - count += 1; - } - return key; - } - - public void flattenProperties(Map properties, String path) { - if (properties == null) { - return; - } - Map propsToUpdate = new HashMap(); - Map modelsToAdd = new HashMap(); - for (String key : properties.keySet()) { - Property property = properties.get(key); - if (property instanceof ObjectProperty && ((ObjectProperty) property).getProperties() != null - && ((ObjectProperty) property).getProperties().size() > 0) { - - ObjectProperty op = (ObjectProperty) property; - - String modelName = resolveModelName(op.getTitle(), path + "_" + key); - Model model = modelFromProperty(op, modelName); - - String existing = matchGenerated(model); - - if (existing != null) { - RefProperty refProperty = new RefProperty(existing); - refProperty.setRequired(op.getRequired()); - propsToUpdate.put(key, refProperty); - } else { - RefProperty refProperty = new RefProperty(modelName); - refProperty.setRequired(op.getRequired()); - propsToUpdate.put(key, refProperty); - modelsToAdd.put(modelName, model); - addGenerated(modelName, model); - swagger.addDefinition(modelName, model); - } - } else if (property instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) property; - Property inner = ap.getItems(); - - if (inner instanceof ObjectProperty) { - ObjectProperty op = (ObjectProperty) inner; - if (op.getProperties() != null && op.getProperties().size() > 0) { - flattenProperties(op.getProperties(), path); - String modelName = resolveModelName(op.getTitle(), path + "_" + key); - Model innerModel = modelFromProperty(op, modelName); - String existing = matchGenerated(innerModel); - if (existing != null) { - RefProperty refProperty = new RefProperty(existing); - refProperty.setRequired(op.getRequired()); - ap.setItems(refProperty); - } else { - RefProperty refProperty = new RefProperty(modelName); - refProperty.setRequired(op.getRequired()); - ap.setItems(refProperty); - addGenerated(modelName, innerModel); - swagger.addDefinition(modelName, innerModel); - } - } - } - } else if (property instanceof MapProperty) { - MapProperty mp = (MapProperty) property; - Property inner = mp.getAdditionalProperties(); - - if (inner instanceof ObjectProperty) { - ObjectProperty op = (ObjectProperty) inner; - if (op.getProperties() != null && op.getProperties().size() > 0) { - flattenProperties(op.getProperties(), path); - String modelName = resolveModelName(op.getTitle(), path + "_" + key); - Model innerModel = modelFromProperty(op, modelName); - String existing = matchGenerated(innerModel); - if (existing != null) { - RefProperty refProperty = new RefProperty(existing); - refProperty.setRequired(op.getRequired()); - mp.setAdditionalProperties(refProperty); - } else { - RefProperty refProperty = new RefProperty(modelName); - refProperty.setRequired(op.getRequired()); - mp.setAdditionalProperties(refProperty); - addGenerated(modelName, innerModel); - swagger.addDefinition(modelName, innerModel); - } - } - } - } - } - if (propsToUpdate.size() > 0) { - for (String key : propsToUpdate.keySet()) { - properties.put(key, propsToUpdate.get(key)); - } - } - for (String key : modelsToAdd.keySet()) { - swagger.addDefinition(key, modelsToAdd.get(key)); - this.addedModels.put(key, modelsToAdd.get(key)); - } - } - - @SuppressWarnings("static-method") - public Model modelFromProperty(ArrayProperty object, @SuppressWarnings("unused") String path) { - String description = object.getDescription(); - String example = null; - - Object obj = object.getExample(); - if (obj != null) { - example = obj.toString(); - } - - Property inner = object.getItems(); - if (inner instanceof ObjectProperty) { - ArrayModel model = new ArrayModel(); - model.setDescription(description); - model.setExample(example); - model.setItems(object.getItems()); - return model; - } - - return null; - } - - public Model modelFromProperty(ObjectProperty object, String path) { - String description = object.getDescription(); - String example = null; - - Object obj = object.getExample(); - if (obj != null) { - example = obj.toString(); - } - String name = object.getName(); - Xml xml = object.getXml(); - Map properties = object.getProperties(); - - ModelImpl model = new ModelImpl(); - model.setDescription(description); - model.setExample(example); - model.setName(name); - model.setXml(xml); - - if (properties != null) { - flattenProperties(properties, path); - model.setProperties(properties); - } - - return model; - } - - @SuppressWarnings("static-method") - public Model modelFromProperty(MapProperty object, @SuppressWarnings("unused") String path) { - String description = object.getDescription(); - String example = null; - - Object obj = object.getExample(); - if (obj != null) { - example = obj.toString(); - } - - ArrayModel model = new ArrayModel(); - model.setDescription(description); - model.setExample(example); - model.setItems(object.getAdditionalProperties()); - - return model; - } - - /** - * Make a RefProperty - * - * @param ref new property name - * @param property Property - * @return {@link Property} A constructed Swagger property - */ - public Property makeRefProperty(String ref, Property property) { - RefProperty newProperty = new RefProperty(ref); - this.copyVendorExtensions(property, newProperty); - return newProperty; - } - - /** - * Copy vendor extensions from Property to another Property - * - * @param source source property - * @param target target property - */ - public void copyVendorExtensions(Property source, AbstractProperty target) { - Map vendorExtensions = source.getVendorExtensions(); - for (String extName : vendorExtensions.keySet()) { - target.setVendorExtension(extName, vendorExtensions.get(extName)); - } - } - - public boolean isSkipMatches() { - return skipMatches; - } - - public void setSkipMatches(boolean skipMatches) { - this.skipMatches = skipMatches; - } - -} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/auth/AuthParser.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/auth/AuthParser.java index 9bff1c2219c5..10595013ede7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/auth/AuthParser.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/auth/AuthParser.java @@ -1,17 +1,14 @@ package org.openapitools.codegen.auth; -import io.swagger.models.auth.AuthorizationValue; +import io.swagger.v3.parser.core.models.AuthorizationValue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import config.ConfigParser; - import static org.apache.commons.lang3.StringUtils.isNotEmpty; public class AuthParser { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java index 39fd7fc866c0..f3c0cdc4e2ee 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java @@ -9,10 +9,12 @@ import org.openapitools.codegen.CodegenConfigLoader; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.auth.AuthParser; -import io.swagger.models.Swagger; -import io.swagger.models.auth.AuthorizationValue; -import io.swagger.parser.SwaggerParser; -import io.swagger.util.Json; +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.core.util.Json; +import io.swagger.v3.parser.core.models.AuthorizationValue; +import io.swagger.v3.parser.core.models.ParseOptions; +import io.swagger.v3.parser.core.models.SwaggerParseResult; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -427,11 +429,12 @@ public ClientOptInput toClientOptInput() { .config(config); final List authorizationValues = AuthParser.parse(auth); - - Swagger swagger = new SwaggerParser().read(inputSpec, authorizationValues, true); - + ParseOptions options = new ParseOptions(); + options.setResolve(true); + options.setFlatten(true); + SwaggerParseResult result = new OpenAPIParser().readLocation(inputSpec, authorizationValues, options); input.opts(new ClientOpts()) - .swagger(swagger); + .openAPI(result.getOpenAPI()); return input; } @@ -464,7 +467,7 @@ private void setVerboseFlags() { return; } LOGGER.info("\nVERBOSE MODE: ON. Additional debug options are injected" + - "\n - [debugSwagger] prints the swagger specification as interpreted by the codegen" + + "\n - [debugSwagger] prints the openapi specification as interpreted by the codegen" + "\n - [debugModels] prints models passed to the template engine" + "\n - [debugOperations] prints operations passed to the template engine" + "\n - [debugSupportingFiles] prints additional data passed to the template engine"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java index f056cca71ea3..b401b931a0a1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java @@ -1,20 +1,30 @@ package org.openapitools.codegen.examples; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.*; -import io.swagger.util.Json; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.BooleanSchema; +import io.swagger.v3.oas.models.media.DateSchema; +import io.swagger.v3.oas.models.media.DateTimeSchema; +import io.swagger.v3.oas.models.media.FileSchema; +import io.swagger.v3.oas.models.media.IntegerSchema; +import io.swagger.v3.oas.models.media.MapSchema; +import io.swagger.v3.oas.models.media.NumberSchema; +import io.swagger.v3.oas.models.media.ObjectSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; +import io.swagger.v3.oas.models.media.UUIDSchema; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.parser.util.SchemaTypeUtil; +import io.swagger.v3.core.util.Json; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.utils.ModelUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.util.*; -import static io.swagger.models.properties.StringProperty.Format.URI; -import static io.swagger.models.properties.StringProperty.Format.URL; - public class ExampleGenerator { - private static final Logger logger = LoggerFactory.getLogger(ExampleGenerator.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ExampleGenerator.class); // TODO: move constants to more appropriate location private static final String MIME_TYPE_JSON = "application/json"; @@ -24,17 +34,20 @@ public class ExampleGenerator { private static final String CONTENT_TYPE = "contentType"; private static final String OUTPUT = "output"; private static final String NONE = "none"; + private static final String URL = "url"; + private static final String URI = "uri"; - protected Map examples; + protected Map examples; private Random random; - public ExampleGenerator(Map examples) { + public ExampleGenerator(Map examples) { this.examples = examples; // use a fixed seed to make the "random" numbers reproducible. this.random = new Random("ExampleGenerator".hashCode()); } - public List> generate(Map examples, List mediaTypes, Property property) { + public List> generate(Map examples, List mediaTypes, Schema property, OpenAPI openAPI) { + LOGGER.debug("debugging generate in ExampleGenerator"); List> output = new ArrayList<>(); Set processedModels = new HashSet<>(); if (examples == null) { @@ -45,9 +58,8 @@ public List> generate(Map examples, List kv = new HashMap<>(); kv.put(CONTENT_TYPE, mediaType); - if (property != null && mediaType.startsWith(MIME_TYPE_JSON)) { - String example = Json.pretty(resolvePropertyToExample("", mediaType, property, processedModels)); - + if (property != null && (mediaType.startsWith(MIME_TYPE_JSON) || mediaType.contains("*/*"))) { + String example = Json.pretty(resolvePropertyToExample("", mediaType, property, processedModels, openAPI)); if (example != null) { kv.put(EXAMPLE, example); output.add(kv); @@ -68,6 +80,7 @@ public List> generate(Map examples, List kv = new HashMap<>(); kv.put(OUTPUT, NONE); @@ -76,7 +89,7 @@ public List> generate(Map examples, List> generate(Map examples, List mediaTypes, String modelName) { + public List> generate(Map examples, List mediaTypes, String modelName, OpenAPI openAPI) { List> output = new ArrayList<>(); Set processedModels = new HashSet<>(); if (examples == null) { @@ -87,11 +100,10 @@ public List> generate(Map examples, List kv = new HashMap<>(); kv.put(CONTENT_TYPE, mediaType); - if (modelName != null && mediaType.startsWith(MIME_TYPE_JSON)) { - final Model model = this.examples.get(modelName); - if (model != null) { - - String example = Json.pretty(resolveModelToExample(modelName, mediaType, model, processedModels)); + if (modelName != null && (mediaType.startsWith(MIME_TYPE_JSON) || mediaType.contains("*/*"))) { + final Schema schema = this.examples.get(modelName); + if (schema != null) { + String example = Json.pretty(resolveModelToExample(modelName, mediaType, schema, processedModels, openAPI)); if (example != null) { kv.put(EXAMPLE, example); @@ -99,8 +111,8 @@ public List> generate(Map examples, ListemptySet()); + final Schema schema = this.examples.get(modelName); + String example = new XmlExampleGenerator(this.examples).toXml(schema, 0, Collections.emptySet()); if (example != null) { kv.put(EXAMPLE, example); output.add(kv); @@ -115,6 +127,7 @@ public List> generate(Map examples, List kv = new HashMap<>(); kv.put(OUTPUT, NONE); @@ -123,95 +136,93 @@ public List> generate(Map examples, List processedModels) { - logger.debug("Resolving example for property {}...", property); + private Object resolvePropertyToExample(String propertyName, String mediaType, Schema property, Set processedModels, OpenAPI openAPI) { + LOGGER.debug("Resolving example for property {}...", property); if (property.getExample() != null) { - logger.debug("Example set in swagger spec, returning example: '{}'", property.getExample().toString()); + LOGGER.debug("Example set in openapi spec, returning example: '{}'", property.getExample().toString()); return property.getExample(); - } else if (property instanceof StringProperty) { - logger.debug("String property"); - String defaultValue = ((StringProperty) property).getDefault(); - if (defaultValue != null && !defaultValue.isEmpty()) { - logger.debug("Default value found: '{}'", defaultValue); - return defaultValue; - } - List enumValues = ((StringProperty) property).getEnum(); - if (enumValues != null && !enumValues.isEmpty()) { - logger.debug("Enum value found: '{}'", enumValues.get(0)); - return enumValues.get(0); - } - String format = property.getFormat(); - if (format != null && (URI.getName().equals(format) || URL.getName().equals(format))) { - logger.debug("URI or URL format, without default or enum, generating random one."); - return "http://example.com/aeiou"; - } - logger.debug("No values found, using property name " + propertyName + " as example"); - return propertyName; - } else if (property instanceof BooleanProperty) { - Boolean defaultValue = ((BooleanProperty) property).getDefault(); + } else if (ModelUtils.isBooleanSchema(property)) { + Object defaultValue = property.getDefault(); if (defaultValue != null) { return defaultValue; } return Boolean.TRUE; - } else if (property instanceof ArrayProperty) { - Property innerType = ((ArrayProperty) property).getItems(); + } else if (ModelUtils.isArraySchema(property)) { + Schema innerType = ((ArraySchema) property).getItems(); if (innerType != null) { - int arrayLength = null == ((ArrayProperty) property).getMaxItems() ? 2 : ((ArrayProperty) property).getMaxItems(); + int arrayLength = null == ((ArraySchema) property).getMaxItems() ? 2 : ((ArraySchema) property).getMaxItems(); Object[] objectProperties = new Object[arrayLength]; - Object objProperty = resolvePropertyToExample(propertyName, mediaType, innerType, processedModels); - for(int i=0; i < arrayLength; i++) { + Object objProperty = resolvePropertyToExample(propertyName, mediaType, innerType, processedModels, openAPI); + for (int i = 0; i < arrayLength; i++) { objectProperties[i] = objProperty; } return objectProperties; } - } else if (property instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(property)) { return "2000-01-23"; - } else if (property instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(property)) { return "2000-01-23T04:56:07.000+00:00"; - } else if (property instanceof DoubleProperty) { - Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue(); - Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue(); - return randomNumber(min, max); - } else if (property instanceof FloatProperty) { - Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue(); - Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue(); - return (float) randomNumber(min, max); - } else if (property instanceof DecimalProperty) { - Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue(); - Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue(); - return new BigDecimal(randomNumber(min, max)); - } else if (property instanceof FileProperty) { + } else if (ModelUtils.isNumberSchema(property)) { + Double min = property.getMinimum() == null ? null : property.getMinimum().doubleValue(); + Double max = property.getMaximum() == null ? null : property.getMaximum().doubleValue(); + if (ModelUtils.isFloatSchema(property)) { // float + return (float) randomNumber(min, max); + } else if (ModelUtils.isDoubleSchema(property)) { // decimal/double + return new BigDecimal(randomNumber(min, max)); + } else { // no format defined + return randomNumber(min, max); + } + } else if (ModelUtils.isFileSchema(property)) { return ""; // TODO - } else if (property instanceof LongProperty) { - Double min = ((BaseIntegerProperty) property).getMinimum() == null ? null : ((BaseIntegerProperty) property).getMinimum().doubleValue(); - Double max = ((BaseIntegerProperty) property).getMaximum() == null ? null : ((BaseIntegerProperty) property).getMaximum().doubleValue(); - return (long) randomNumber(min, max); - } else if (property instanceof BaseIntegerProperty) { // Includes IntegerProperty - Double min = ((BaseIntegerProperty) property).getMinimum() == null ? null : ((BaseIntegerProperty) property).getMinimum().doubleValue(); - Double max = ((BaseIntegerProperty) property).getMaximum() == null ? null : ((BaseIntegerProperty) property).getMaximum().doubleValue(); + + } else if (ModelUtils.isIntegerSchema(property)) { + Double min = property.getMinimum() == null ? null : property.getMinimum().doubleValue(); + Double max = property.getMaximum() == null ? null : property.getMaximum().doubleValue(); + if (ModelUtils.isLongSchema(property)) { + return (long) randomNumber(min, max); + } return (int) randomNumber(min, max); - } else if (property instanceof MapProperty) { + } else if (ModelUtils.isMapSchema(property)) { Map mp = new HashMap(); if (property.getName() != null) { mp.put(property.getName(), - resolvePropertyToExample(propertyName, mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels)); + resolvePropertyToExample(propertyName, mediaType, (Schema) property.getAdditionalProperties(), processedModels, openAPI)); } else { mp.put("key", - resolvePropertyToExample(propertyName, mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels)); + resolvePropertyToExample(propertyName, mediaType, (Schema) property.getAdditionalProperties(), processedModels, openAPI)); } return mp; - } else if (property instanceof ObjectProperty) { - return "{}"; - } else if (property instanceof RefProperty) { - String simpleName = ((RefProperty) property).getSimpleRef(); - logger.debug("Ref property, simple name: {}", simpleName); - Model model = examples.get(simpleName); - if (model != null) { - return resolveModelToExample(simpleName, mediaType, model, processedModels); + } else if (ModelUtils.isUUIDSchema(property)) { + return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; + } else if (ModelUtils.isStringSchema(property)) { + LOGGER.debug("String property"); + String defaultValue = (String) property.getDefault(); + if (defaultValue != null && !defaultValue.isEmpty()) { + LOGGER.debug("Default value found: '{}'", defaultValue); + return defaultValue; + } + List enumValues = property.getEnum(); + if (enumValues != null && !enumValues.isEmpty()) { + LOGGER.debug("Enum value found: '{}'", enumValues.get(0)); + return enumValues.get(0); + } + String format = property.getFormat(); + if (format != null && (URI.equals(format) || URL.equals(format))) { + LOGGER.debug("URI or URL format, without default or enum, generating random one."); + return "http://example.com/aeiou"; } - logger.warn("Ref property with empty model."); - } else if (property instanceof UUIDProperty) { - return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; + LOGGER.debug("No values found, using property name " + propertyName + " as example"); + return propertyName; + } else if (!StringUtils.isEmpty(property.get$ref())) { // model + String simpleName = ModelUtils.getSimpleRef(property.get$ref()); + Schema schema = ModelUtils.getSchema(openAPI, simpleName); + if (schema == null) { // couldn't find the model/schema + return "{}"; + } + return resolveModelToExample(simpleName, mediaType, schema, processedModels, openAPI); + + } else if (ModelUtils.isObjectSchema(property)) { + return "{}"; } return ""; @@ -230,30 +241,28 @@ private double randomNumber(Double min, Double max) { } } - private Object resolveModelToExample(String name, String mediaType, Model model, Set processedModels) { + private Object resolveModelToExample(String name, String mediaType, Schema schema, Set processedModels, OpenAPI openAPI) { if (processedModels.contains(name)) { - return model.getExample(); + return schema.getExample(); } - if (model instanceof ModelImpl) { - processedModels.add(name); - ModelImpl impl = (ModelImpl) model; - Map values = new HashMap<>(); - logger.debug("Resolving model '{}' to example", name); - - if (impl.getExample() != null) { - logger.debug("Using example from spec: {}", impl.getExample()); - return impl.getExample(); - } else if (impl.getProperties() != null) { - logger.debug("Creating example from model values"); - for (String propertyName : impl.getProperties().keySet()) { - Property property = impl.getProperties().get(propertyName); - values.put(propertyName, resolvePropertyToExample(propertyName, mediaType, property, processedModels)); - } - impl.setExample(values); + processedModels.add(name); + Map values = new HashMap<>(); + LOGGER.debug("Resolving model '{}' to example", name); + if (schema.getExample() != null) { + LOGGER.debug("Using example from spec: {}", schema.getExample()); + return schema.getExample(); + } else if (schema.getProperties() != null) { + LOGGER.debug("Creating example from model values"); + for (Object propertyName : schema.getProperties().keySet()) { + Schema property = (Schema) schema.getProperties().get(propertyName.toString()); + values.put(propertyName.toString(), resolvePropertyToExample(propertyName.toString(), mediaType, property, processedModels, openAPI)); } - return values; + schema.setExample(values); + return schema.getExample(); + } else { + // TODO log an error message as the model does not have any properties + return null; } - return ""; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/XmlExampleGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/XmlExampleGenerator.java index 42f7a236e9d8..9922b3d9685c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/XmlExampleGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/XmlExampleGenerator.java @@ -1,27 +1,20 @@ package org.openapitools.codegen.examples; - -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.RefModel; -import io.swagger.models.Xml; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.DecimalProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.BaseIntegerProperty; -import io.swagger.models.properties.AbstractNumericProperty; -import io.swagger.models.properties.PasswordProperty; -import io.swagger.models.properties.UUIDProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.BooleanSchema; +import io.swagger.v3.oas.models.media.DateSchema; +import io.swagger.v3.oas.models.media.DateTimeSchema; +import io.swagger.v3.oas.models.media.IntegerSchema; +import io.swagger.v3.oas.models.media.NumberSchema; +import io.swagger.v3.oas.models.media.PasswordSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; +import io.swagger.v3.oas.models.media.UUIDSchema; +import io.swagger.v3.oas.models.media.XML; +import io.swagger.v3.parser.util.SchemaTypeUtil; import org.apache.commons.lang3.StringUtils; - +import org.openapitools.codegen.utils.ModelUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,34 +33,32 @@ public class XmlExampleGenerator { public static String CLOSE_TAG = ">"; public static String TAG_END = " examples; + protected Map examples; - public XmlExampleGenerator(Map examples) { + public XmlExampleGenerator(Map examples) { this.examples = examples; if (examples == null) { - this.examples = new HashMap(); + this.examples = new HashMap(); } } - public String toXml(Property property) { - return toXml(null, property, 0, Collections.emptySet()); + public String toXml(Schema schema) { + return toXml(null, schema, 0, Collections.emptySet()); } - protected String toXml(Model model, int indent, Collection path) { - if (model instanceof RefModel) { - RefModel ref = (RefModel) model; - Model actualModel = examples.get(ref.getSimpleRef()); - if (actualModel instanceof ModelImpl) { - return modelImplToXml((ModelImpl) actualModel, indent, path); + protected String toXml(Schema schema, int indent, Collection path) { + if (schema == null) return ""; + if (StringUtils.isNotEmpty(schema.get$ref())) { + Schema actualSchema = examples.get(schema.get$ref()); + if (actualSchema != null) { + return modelImplToXml(actualSchema, indent, path); } - } else if (model instanceof ModelImpl) { - return modelImplToXml((ModelImpl) model, indent, path); } - return null; + return modelImplToXml(schema, indent, path); } - protected String modelImplToXml(ModelImpl model, int indent, Collection path) { - final String modelName = model.getName(); + protected String modelImplToXml(Schema schema, int indent, Collection path) { + final String modelName = schema.getName(); if (path.contains(modelName)) { return EMPTY; } @@ -76,38 +67,40 @@ protected String modelImplToXml(ModelImpl model, int indent, Collection StringBuilder sb = new StringBuilder(); // attributes - Map attributes = new LinkedHashMap(); - Map elements = new LinkedHashMap(); + Map attributes = new LinkedHashMap(); + Map elements = new LinkedHashMap(); String name = modelName; - Xml xml = model.getXml(); + XML xml = schema.getXml(); if (xml != null) { if (xml.getName() != null) { name = xml.getName(); } } // TODO: map objects will not enter this block - if(model.getProperties() != null) { - for (String pName : model.getProperties().keySet()) { - Property p = model.getProperties().get(pName); - if (p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute()) { - attributes.put(pName, p); + Map properties = schema.getProperties(); + if (properties != null && !properties.isEmpty()) { + for (String pName : properties.keySet()) { + Schema property = properties.get(pName); + if (property != null && property.getXml() != null && property.getXml().getAttribute() != null && property.getXml().getAttribute()) { + attributes.put(pName, property); } else { - elements.put(pName, p); + elements.put(pName, property); } } } + sb.append(indent(indent)).append(TAG_START); sb.append(name); for (String pName : attributes.keySet()) { - Property p = attributes.get(pName); - sb.append(" ").append(pName).append("=").append(quote(toXml(null, p, 0, selfPath))); + Schema s = attributes.get(pName); + sb.append(" ").append(pName).append("=").append(quote(toXml(null, s, 0, selfPath))); } sb.append(CLOSE_TAG); sb.append(NEWLINE); for (String pName : elements.keySet()) { - Property p = elements.get(pName); - final String asXml = toXml(pName, p, indent + 1, selfPath); + Schema s = elements.get(pName); + final String asXml = toXml(pName, s, indent + 1, selfPath); if (StringUtils.isEmpty(asXml)) { continue; } @@ -124,17 +117,17 @@ protected String quote(String string) { return "\"" + string + "\""; } - protected String toXml(String name, Property property, int indent, Collection path) { - if (property == null) { + protected String toXml(String name, Schema schema, int indent, Collection path) { + if (schema == null) { return ""; } StringBuilder sb = new StringBuilder(); - if (property instanceof ArrayProperty) { - ArrayProperty p = (ArrayProperty) property; - Property inner = p.getItems(); + if (ModelUtils.isArraySchema(schema)) { + ArraySchema as = (ArraySchema) schema; + Schema inner = as.getItems(); boolean wrapped = false; - if (property.getXml() != null && property.getXml().getWrapped() != null && property.getXml().getWrapped()) { + if (schema.getXml() != null && schema.getXml().getWrapped() != null && schema.getXml().getWrapped()) { wrapped = true; } if (wrapped) { @@ -156,16 +149,15 @@ protected String toXml(String name, Property property, int indent, Collection * Ada programming standard avoid the camelcase syntax and prefer the underscore * notation. We also have to make sure the identifier is not a reserved keyword. * When this happens, we add the configurable prefix. The function translates: - * + *

* body - P_Body * petId - Pet_Id * updatePetWithForm - Update_Pet_With_Form * - * @param name the parameter name. + * @param name the parameter name. * @param prefix the optional prefix in case the parameter name is a reserved keyword. * @return the Ada identifier to be used. */ @@ -231,7 +228,7 @@ public String toModelName(final String name) { } @Override - public CodegenProperty fromProperty(String name, Property p) { + public CodegenProperty fromProperty(String name, Schema p) { CodegenProperty property = super.fromProperty(name, p); if (property != null) { String nameInCamelCase = property.nameInCamelCase; @@ -266,7 +263,7 @@ public String escapeUnsafeCharacters(String input) { /** * Override the Mustache compiler configuration. - * + *

* We don't want to have special characters escaped * * @param compiler the compiler. @@ -285,24 +282,23 @@ public Mustache.Compiler processCompiler(Mustache.Compiler compiler) { * for different property types * * @return a string value used as the `dataType` field for model templates, - * `returnType` for api templates + * `returnType` for api templates */ @Override - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); + public String getTypeDeclaration(Schema p) { + String schemaType = getSchemaType(p); - if (swaggerType != null) { - swaggerType = swaggerType.replace("-", "_"); + if (schemaType != null) { + schemaType = schemaType.replace("-", "_"); } - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return getTypeDeclaration(inner) + "_Vectors.Vector"; } - if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); String name = getTypeDeclaration(inner) + "_Map"; if (name.startsWith("Swagger.")) { return name; @@ -310,20 +306,20 @@ public String getTypeDeclaration(Property p) { return "Swagger." + name; } } - if (typeMapping.containsKey(swaggerType)) { - if (p.getRequired()) { - return typeMapping.get(swaggerType); + // TODO need to revise/test the logic below to check "required" + if (typeMapping.containsKey(schemaType)) { + if (p.getRequired() != null && p.getRequired().contains(p.getName())) { + return typeMapping.get(schemaType); } else { - return nullableTypeMapping.get(swaggerType); + return nullableTypeMapping.get(schemaType); } } - // LOGGER.info("Swagger type " + swaggerType); - if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; + // LOGGER.info("Swagger type " + schemaType); + if (languageSpecificPrimitives.contains(schemaType)) { + return schemaType; } - String modelType = toModelName(swaggerType).replace("-", "_"); - if (p instanceof StringProperty || p instanceof DateProperty - || p instanceof DateTimeProperty || p instanceof FileProperty + String modelType = toModelName(schemaType).replace("-", "_"); + if (ModelUtils.isStringSchema(p) || ModelUtils.isFileSchema(p) || languageSpecificPrimitives.contains(modelType)) { return modelType; } @@ -338,7 +334,7 @@ public String getTypeDeclaration(Property p) { * @param parameter CodegenParameter object to be processed. */ @Override - public void postProcessParameter(CodegenParameter parameter){ + public void postProcessParameter(CodegenParameter parameter) { // Give the base class a chance to process super.postProcessParameter(parameter); @@ -355,7 +351,7 @@ public void postProcessParameter(CodegenParameter parameter){ /** * Post process the media types (produces and consumes) for Ada code generator. - * + *

* For each media type, add a adaMediaType member that gives the Ada enum constant * for the corresponding type. * @@ -379,19 +375,16 @@ protected int postProcessMediaTypes(List> types) { @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, - Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + Map definitions, OpenAPI openAPI) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, openAPI); if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { - Response methodResponse = findMethodResponse(operation.getResponses()); - - if (methodResponse != null) { - if (methodResponse.getSchema() != null) { - CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); - op.vendorExtensions.put("x-codegen-response", cm); - if(cm.datatype == "HttpContent") { - op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); - } + ApiResponse methodResponse = findMethodResponse(operation.getResponses()); + if (methodResponse != null && getSchemaFromResponse(methodResponse) != null) { + CodegenProperty cm = fromProperty("response", getSchemaFromResponse(methodResponse)); + op.vendorExtensions.put("x-codegen-response", cm); + if ("HttpContent".equals(cm.datatype)) { + op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); } } } @@ -499,7 +492,7 @@ public Map postProcessModels(Map objs) { List> revisedOrderedModels = new ArrayList>(); List collectedModelNames = new ArrayList(); int sizeOrderedModels = orderedModels.size(); - for (int i=0;i independentModel = null; String independentModelName = null; for (Map model : orderedModels) { @@ -538,8 +531,10 @@ public Map postProcessModels(Map objs) { @Override public Map postProcessSupportingFileData(Map objs) { objs.put("orderedModels", orderedModels); - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { + generateJSONSpecFile(objs); + /* TODO do we still need the SWAGGER_HOST logic below + Swagger swagger = (Swagger) objs.get("swagger"); + if (swagger != null) { String host = swagger.getBasePath(); try { swagger.setHost("SWAGGER_HOST"); @@ -548,7 +543,7 @@ public Map postProcessSupportingFileData(Map obj LOGGER.error(e.getMessage(), e); } swagger.setHost(host); - } + }*/ /** * Collect the scopes to generate unique identifiers for each of them. 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 641d557c8d30..6aad023a1810 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 @@ -2,11 +2,19 @@ import com.google.common.collect.ImmutableMap; import com.samskivert.mustache.Mustache; +import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; -import org.openapitools.codegen.mustache.*; +import org.openapitools.codegen.utils.*; import org.openapitools.codegen.utils.ModelUtils; -import io.swagger.models.properties.*; -import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.mustache.*; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.core.util.Yaml; +import io.swagger.v3.parser.util.SchemaTypeUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -78,7 +86,7 @@ public AbstractCSharpCodegen() { // fully qualified name "Client", "client", "parameter", // local variable names in API methods (endpoints) - "localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams", + "localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams", "localVarFormParams", "localVarFileParams", "localVarStatusCode", "localVarResponse", "localVarPostBody", "localVarHttpHeaderAccepts", "localVarHttpHeaderAccept", "localVarHttpContentTypes", "localVarHttpContentType", @@ -176,18 +184,6 @@ public void setNetCoreProjectFileFlag(boolean flag) { this.netCoreProjectFileFlag = flag; } - protected void addOption(String key, String description, String defaultValue) { - CliOption option = new CliOption(key, description); - if (defaultValue != null) option.defaultValue(defaultValue); - cliOptions.add(option); - } - - protected void addSwitch(String key, String description, Boolean defaultValue) { - CliOption option = CliOption.newBoolean(key, description); - if (defaultValue != null) option.defaultValue(defaultValue.toString()); - cliOptions.add(option); - } - public void useDateTimeOffset(boolean flag) { this.useDateTimeOffsetFlag = flag; if (flag) typeMapping.put("datetime", "DateTimeOffset?"); @@ -222,14 +218,14 @@ public void processOpts() { if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { LOGGER.warn(String.format("%s is not used by C# generators. Please use %s", CodegenConstants.INVOKER_PACKAGE, CodegenConstants.PACKAGE_NAME)); } - + // {{packageTitle}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_TITLE)) { setPackageTitle((String) additionalProperties.get(CodegenConstants.PACKAGE_TITLE)); } else { additionalProperties.put(CodegenConstants.PACKAGE_TITLE, packageTitle); } - + // {{packageProductName}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_PRODUCTNAME)) { setPackageProductName((String) additionalProperties.get(CodegenConstants.PACKAGE_PRODUCTNAME)); @@ -243,14 +239,14 @@ public void processOpts() { } else { additionalProperties.put(CodegenConstants.PACKAGE_DESCRIPTION, packageDescription); } - + // {{packageCompany}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_COMPANY)) { setPackageCompany((String) additionalProperties.get(CodegenConstants.PACKAGE_COMPANY)); } else { additionalProperties.put(CodegenConstants.PACKAGE_COMPANY, packageCompany); } - + // {{packageCopyright}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_COPYRIGHT)) { setPackageCopyright((String) additionalProperties.get(CodegenConstants.PACKAGE_COPYRIGHT)); @@ -264,7 +260,7 @@ public void processOpts() { } else { additionalProperties.put(CodegenConstants.PACKAGE_AUTHORS, packageAuthors); } - + // {{useDateTimeOffset}} if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_OFFSET)) { useDateTimeOffset(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_DATETIME_OFFSET)); @@ -298,9 +294,9 @@ public void processOpts() { if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) { String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString(); - if("false".equals(useInterfacePrefix.toLowerCase())) { + if ("false".equals(useInterfacePrefix.toLowerCase())) { setInterfacePrefix(""); - } else if(!"true".equals(useInterfacePrefix.toLowerCase())) { + } else if (!"true".equals(useInterfacePrefix.toLowerCase())) { // NOTE: if user passes "true" explicitly, we use the default I- prefix. The other supported case here is a custom prefix. setInterfacePrefix(sanitizeName(useInterfacePrefix)); } @@ -368,7 +364,7 @@ public Map postProcessModels(Map objs) { */ @Override public Map postProcessAllModels(Map objs) { - final Map processed = super.postProcessAllModels(objs); + final Map processed = super.postProcessAllModels(objs); postProcessEnumRefs(processed); return processed; } @@ -376,13 +372,14 @@ public Map postProcessAllModels(Map objs) { /** * C# differs from other languages in that Enums are not _true_ objects; enums are compiled to integral types. * So, in C#, an enum is considers more like a user-defined primitive. - * + *

* When working with enums, we can't always assume a RefModel is a nullable type (where default(YourType) == null), * so this post processing runs through all models to find RefModel'd enums. Then, it runs through all vars and modifies * those vars referencing RefModel'd enums to work the same as inlined enums rather than as objects. + * * @param models processed models to be further processed for enum references */ - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({"unchecked"}) private void postProcessEnumRefs(final Map models) { Map enumRefs = new HashMap(); for (Map.Entry entry : models.entrySet()) { @@ -438,7 +435,7 @@ private void postProcessEnumRefs(final Map models) { // Since we iterate enumVars for modelnnerEnum and enumClass templates, and CodegenModel is missing some of CodegenProperty's properties, // we can take advantage of Mustache's contextual lookup to add the same "properties" to the model's enumVars scope rather than CodegenProperty's scope. - List> enumVars = (ArrayList>)model.allowableValues.get("enumVars"); + List> enumVars = (ArrayList>) model.allowableValues.get("enumVars"); List> newEnumVars = new ArrayList>(); for (Map enumVar : enumVars) { Map mixedVars = new HashMap(); @@ -535,15 +532,13 @@ public Map postProcessOperations(Map objs) { } } - if (operation.examples != null){ - for (Map example : operation.examples) - { - for (Map.Entry entry : example.entrySet()) - { + if (operation.examples != null) { + for (Map example : operation.examples) { + for (Map.Entry entry : example.entrySet()) { // Replace " with \", \r, \n with \\r, \\n String val = entry.getValue().replace("\"", "\\\"") - .replace("\r","\\r") - .replace("\n","\\n"); + .replace("\r", "\\r") + .replace("\n", "\\n"); entry.setValue(val); } } @@ -638,11 +633,11 @@ public String toParamName(String name) { } return name; - } + } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -655,40 +650,26 @@ public String escapeReservedWord(String name) { * @return string presentation of the example value of the property */ @Override - public String toExampleValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getExample() != null) { - return "\"" + dp.getExample().toString() + "\""; + public String toExampleValue(Schema p) { + if (ModelUtils.isStringSchema(p)) { + if (p.getExample() != null) { + return "\"" + p.getExample().toString() + "\""; } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getExample() != null) { - return dp.getExample().toString(); + } else if (ModelUtils.isBooleanSchema(p)) { + if (p.getExample() != null) { + return p.getExample().toString(); } - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { // TODO - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { // TODO - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getExample() != null) { - return dp.getExample().toString(); - } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getExample() != null) { - return dp.getExample().toString(); + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getExample() != null) { + return p.getExample().toString(); } - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getExample() != null) { - return dp.getExample().toString(); - } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getExample() != null) { - return dp.getExample().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getExample() != null) { + return p.getExample().toString(); } } @@ -702,46 +683,32 @@ public String toExampleValue(Property p) { * @return string presentation of the default value of the property */ @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - String _default = dp.getDefault(); - if (dp.getEnum() == null) { - return "\"" + _default + "\""; - } else { - // convert to enum var name later in postProcessModels - return _default; - } - } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { // TODO - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { // TODO - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return String.format("%1$sF", dp.getDefault()); + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + String _default = (String) p.getDefault(); + if (p.getEnum() == null) { + return "\"" + _default + "\""; + } else { + // convert to enum var name later in postProcessModels + return _default; + } } } @@ -755,39 +722,40 @@ protected boolean isReservedWord(String word) { } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type; - if (swaggerType == null) { - swaggerType = ""; // set swagger type to empty string if null + if (openAPIType == null) { + openAPIType = ""; // set swagger type to empty string if null } // NOTE: typeMapping here supports things like string/String, long/Long, datetime/DateTime as lowercase keys. // Should we require explicit casing here (values are not insensitive). // TODO avoid using toLowerCase as typeMapping should be case-sensitive - if (typeMapping.containsKey(swaggerType.toLowerCase())) { - type = typeMapping.get(swaggerType.toLowerCase()); + if (typeMapping.containsKey(openAPIType.toLowerCase())) { + type = typeMapping.get(openAPIType.toLowerCase()); if (languageSpecificPrimitives.contains(type)) { return type; } } else { - type = swaggerType; + type = openAPIType; } return toModelName(type); } /** * Provides C# strongly typed declaration for simple arrays of some type and arrays of arrays of some type. + * * @param arr The input array property * @return The type declaration when the type is an array of arrays. */ - private String getArrayTypeDeclaration(ArrayProperty arr) { + private String getArrayTypeDeclaration(ArraySchema arr) { // TODO: collection type here should be fully qualified namespace to avoid model conflicts // This supports arrays of arrays. String arrayType = typeMapping.get("array"); StringBuilder instantiationType = new StringBuilder(arrayType); - Property items = arr.getItems(); + Schema items = arr.getItems(); String nestedType = getTypeDeclaration(items); // TODO: We may want to differentiate here between generics and primitive arrays. instantiationType.append("<").append(nestedType).append(">"); @@ -795,22 +763,21 @@ private String getArrayTypeDeclaration(ArrayProperty arr) { } @Override - public String toInstantiationType(Property p) { - if (p instanceof ArrayProperty) { - return getArrayTypeDeclaration((ArrayProperty) p); + public String toInstantiationType(Schema p) { + if (ModelUtils.isArraySchema(p)) { + return getArrayTypeDeclaration((ArraySchema) p); } return super.toInstantiationType(p); } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - return getArrayTypeDeclaration((ArrayProperty) p); - } else if (p instanceof MapProperty) { + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + return getArrayTypeDeclaration((ArraySchema) p); + } else if (ModelUtils.isMapSchema(p)) { // Should we also support maps of maps? - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + ""; } return super.getTypeDeclaration(p); } @@ -876,11 +843,11 @@ public void setPackageName(String packageName) { public void setPackageVersion(String packageVersion) { this.packageVersion = packageVersion; } - + public void setPackageTitle(String packageTitle) { this.packageTitle = packageTitle; } - + public void setPackageProductName(String packageProductName) { this.packageProductName = packageProductName; } @@ -888,11 +855,11 @@ public void setPackageProductName(String packageProductName) { public void setPackageDescription(String packageDescription) { this.packageDescription = packageDescription; } - + public void setPackageCompany(String packageCompany) { this.packageCompany = packageCompany; } - + public void setPackageCopyright(String packageCopyright) { this.packageCopyright = packageCopyright; } @@ -900,7 +867,7 @@ public void setPackageCopyright(String packageCopyright) { public void setPackageAuthors(String packageAuthors) { this.packageAuthors = packageAuthors; } - + public void setSourceFolder(String sourceFolder) { this.sourceFolder = sourceFolder; } @@ -919,7 +886,7 @@ public String toEnumValue(String value, String datatype) { // Per: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. // but we're not supporting unsigned integral types or shorts. - if(datatype.startsWith("int") || datatype.startsWith("long") || datatype.startsWith("byte")) { + if (datatype.startsWith("int") || datatype.startsWith("long") || datatype.startsWith("byte")) { return value; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java index ea54c581d2a0..c9708dd38e55 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java @@ -3,7 +3,10 @@ import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.DefaultCodegen; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import java.util.Arrays; @@ -58,6 +61,7 @@ public AbstractCppCodegen() { "if", "inline", "int", + "linux", "long", "mutable", "namespace", @@ -134,7 +138,7 @@ public String toVarName(String name) { */ @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return sanitizeName("_" + name); @@ -155,7 +159,7 @@ public String toParamName(String name) { } @Override - public CodegenProperty fromProperty(String name, Property p) { + public CodegenProperty fromProperty(String name, Schema p) { CodegenProperty property = super.fromProperty(name, p); String nameInCamelCase = property.nameInCamelCase; if (nameInCamelCase.length() > 1) { @@ -166,7 +170,7 @@ public CodegenProperty fromProperty(String name, Property p) { property.nameInCamelCase = nameInCamelCase; return property; } - + /** * Output the Getter name for boolean property, e.g. isActive * @@ -176,4 +180,9 @@ public CodegenProperty fromProperty(String name, Property p) { public String toBooleanGetter(String name) { return "is" + getterAndSetterCapitalize(name); } + + @Override + public String getTypeDeclaration(String str) { + return "std::shared_ptr<" + toModelName(str) + ">"; + } } 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 d4e6fbb395c6..7f35150e3a32 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 @@ -13,32 +13,33 @@ import java.util.Set; import org.apache.commons.lang3.StringUtils; - import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenParameter; import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.*; import org.openapitools.codegen.utils.ModelUtils; -import io.swagger.models.Model; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.util.Json; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.core.util.Json; public abstract class AbstractEiffelCodegen extends DefaultCodegen implements CodegenConfig { private final Set parentModels = new HashSet<>(); private final Multimap childrenByParent = ArrayListMultimap.create(); - - public AbstractEiffelCodegen(){ + + public AbstractEiffelCodegen() { super(); + + hideGenerationTimestamp = Boolean.FALSE; + setReservedWordsLowerCase(Arrays.asList( // language reserved words "across", "agent", "alias", "all", "and", "as", "assign", "attribute", "check", "class", "convert", @@ -55,7 +56,7 @@ public AbstractEiffelCodegen(){ "NATURAL_16", "NATURAL_32", "NATURAL_64", "REAL_32", "REAL_64")); instantiationTypes.clear(); - + typeMapping.clear(); typeMapping.put("integer", "INTEGER_32"); typeMapping.put("long", "INTEGER_64"); @@ -72,7 +73,7 @@ public AbstractEiffelCodegen(){ typeMapping.put("File", "FILE"); typeMapping.put("file", "FILE"); typeMapping.put("binary", "STRING_32"); - typeMapping.put("ByteArray", "ARRAY [NATURAL_8]"); + typeMapping.put("ByteArray", "ARRAY [NATURAL_8]"); typeMapping.put("object", "ANY"); typeMapping.put("map", "STRING_TABLE"); typeMapping.put("array", "LIST"); @@ -89,9 +90,9 @@ public AbstractEiffelCodegen(){ cliOptions .add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Eiffel package version.").defaultValue("1.0.0")); cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - "hides the timestamp when files were generated").defaultValue(Boolean.TRUE.toString())); + CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC).defaultValue(Boolean.TRUE.toString())); } - + @Override public String escapeReservedWord(String name) { // Can't start with an underscore, as our fields need to start with an @@ -110,7 +111,7 @@ public String escapeReservedWord(String name) { } if (name.matches("^\\d.*")) {// prepend var_ return "var_" + name; - } + } return "var_" + name; } @@ -127,8 +128,8 @@ public String toVarName(String name) { // pet_id // petId => pet_id name = unCamelize(name); - - if (name.startsWith("_")){ + + if (name.startsWith("_")) { name = "var" + name; } @@ -173,7 +174,7 @@ public String toModelFilename(String name) { if (isReservedWord(name)) { LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after - // camelize) + // camelize) } // model name starts with number @@ -181,7 +182,7 @@ public String toModelFilename(String name) { LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + ("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response - // (after camelize) + // (after camelize) } return underscore(name); @@ -191,8 +192,8 @@ public String toModelFilename(String name) { public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at name = name.replaceAll("-", "_"); // FIXME: a parameter should not be - // assigned. Also declare the - // methods parameters as 'final'. + // assigned. Also declare the + // methods parameters as 'final'. // e.g. PetApi.go => pet_api.go return underscore(name) + "_api"; @@ -217,8 +218,7 @@ public String toApiName(String name) { * lowercase letter, but we need that param to be exportable (starts with an * Uppercase letter). * - * @param parameter - * CodegenParameter object to be processed. + * @param parameter CodegenParameter object to be processed. */ @Override public void postProcessParameter(CodegenParameter parameter) { @@ -264,47 +264,46 @@ public String toApiDocFilename(String name) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return "LIST [" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; } // return super.getTypeDeclaration(p); // Not using the supertype invocation, because we want to UpperCamelize // the type. - String swaggerType = getSwaggerType(p); - if (typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); + String scheamType = getSchemaType(p); + if (typeMapping.containsKey(scheamType)) { + return typeMapping.get(scheamType); } - if (typeMapping.containsValue(swaggerType)) { - return swaggerType; + if (typeMapping.containsValue(scheamType)) { + return scheamType; } - if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; + if (languageSpecificPrimitives.contains(scheamType)) { + return scheamType; } - return toModelName(swaggerType); + return toModelName(scheamType); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String scheamType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(scheamType)) { + type = typeMapping.get(scheamType); if (languageSpecificPrimitives.contains(type)) return (type); } else - type = swaggerType; + type = scheamType; return type; } @@ -451,18 +450,18 @@ private void processParentPropertiesInChildModel(final CodegenModel parent, fina } } } - + @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { - final Model parentModel = allDefinitions.get(codegenModel.parentSchema); + final Schema parentModel = allDefinitions.get(codegenModel.parentSchema); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); codegenModel = AbstractEiffelCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); } return codegenModel; } - + private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { // This generator uses inline classes to define enums, which breaks when // dealing with models that have subTypes. To clean this up, we will analyze @@ -471,7 +470,7 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code // Because the child models extend the parents, the enums will be available via the parent. // Only bother with reconciliation if the parent model has enums. - if (!parentCodegenModel.hasEnums) { + if (!parentCodegenModel.hasEnums) { return codegenModel; } @@ -499,10 +498,10 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code } } - if(removedChildEnum) { + if (removedChildEnum) { // If we removed an entry from this model's vars, we need to ensure hasMore is updated int count = 0, numVars = codegenProperties.size(); - for(CodegenProperty codegenProperty : codegenProperties) { + for (CodegenProperty codegenProperty : codegenProperties) { count += 1; codegenProperty.hasMore = (count < numVars) ? true : false; } @@ -511,7 +510,7 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code return codegenModel; } - + @Override protected boolean needToImport(String type) { return !defaultIncludes.contains(type) && !languageSpecificPrimitives.contains(type); @@ -534,22 +533,21 @@ public Map createMapping(String key, String value) { return customImport; } - + @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - Property additionalProperties2 = ap.getAdditionalProperties(); + public String toInstantiationType(Schema p) { + if (ModelUtils.isMapSchema(p)) { + Schema additionalProperties2 = (Schema) p.getAdditionalProperties(); String type = additionalProperties2.getType(); if (null == type) { - LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" // - + "\tIn Property: " + p); + LOGGER.error("No Type defined for Additional Schema " + additionalProperties2 + "\n" // + + "\tIn Schema: " + p); } - String inner = toModelName(getSwaggerType(additionalProperties2)); + String inner = toModelName(getSchemaType(additionalProperties2)); return instantiationTypes.get("map") + " [" + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = toModelName(getSwaggerType(ap.getItems())); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = toModelName(getSchemaType(ap.getItems())); return instantiationTypes.get("array") + " [" + inner + "]"; } else { return null; @@ -570,7 +568,8 @@ public String toEiffelFeatureStyle(String operationId) { /** * Update property for array(list) container - * @param property Codegen property + * + * @param property Codegen property * @param innerProperty Codegen inner property of map or list */ @Override @@ -587,10 +586,10 @@ protected void updatePropertyForArray(CodegenProperty property, CodegenProperty } property.items = innerProperty; // inner item is Enum - if (isPropertyInnerMostEnum(property)) { + if (isPropertyInnerMostEnum(property)) { // We use the data type instead of the Enum class. // at the moment is not supported. - + // isEnum is set to true when the type is an enum // or the inner type of an array/map is an enum //property.isEnum = true; @@ -601,6 +600,6 @@ protected void updatePropertyForArray(CodegenProperty property, CodegenProperty //property.allowableValues = getInnerEnumAllowableValues(property); } - } - + } + } 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 921bc63f92fe..8178ed30e8ee 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 @@ -1,12 +1,11 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.Swagger; -import io.swagger.util.Yaml; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.core.util.Yaml; import java.util.*; @@ -28,6 +27,8 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege public AbstractGoCodegen() { super(); + hideGenerationTimestamp = Boolean.FALSE; + defaultIncludes = new HashSet( Arrays.asList( "map", @@ -84,7 +85,7 @@ public AbstractGoCodegen() { cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).") .defaultValue("swagger")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); } @@ -224,49 +225,47 @@ public void postProcessParameter(CodegenParameter parameter){ } @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if(ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return "[]" + getTypeDeclaration(inner); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[string]" + getTypeDeclaration(inner); + else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[string]" + getTypeDeclaration(inner); } //return super.getTypeDeclaration(p); // Not using the supertype invocation, because we want to UpperCamelize // the type. - String swaggerType = getSwaggerType(p); - if (typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); + String openAPIType = getSchemaType(p); + if (typeMapping.containsKey(openAPIType)) { + return typeMapping.get(openAPIType); } - if(typeMapping.containsValue(swaggerType)) { - return swaggerType; + if(typeMapping.containsValue(openAPIType)) { + return openAPIType; } - if(languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; + if(languageSpecificPrimitives.contains(openAPIType)) { + return openAPIType; } - return toModelName(swaggerType); + return toModelName(openAPIType); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if(typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if(languageSpecificPrimitives.contains(type)) return (type); } else - type = swaggerType; + type = openAPIType; return type; } @@ -374,14 +373,7 @@ public Map postProcessModels(Map objs) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { - try { - objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } + generateYAMLSpecFile(objs); return super.postProcessSupportingFileData(objs); } 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 109d21b4e2c4..20ae625adde1 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 @@ -2,14 +2,18 @@ import java.io.File; import java.util.Arrays; +import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; +import java.util.Set; import java.util.regex.Pattern; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.parser.util.SchemaTypeUtil; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; @@ -18,31 +22,12 @@ import com.google.common.base.Strings; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenParameter; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.Swagger; -import io.swagger.models.parameters.BodyParameter; -import io.swagger.models.parameters.FormParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; - +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.parameters.*; public abstract class AbstractJavaCodegen extends DefaultCodegen implements CodegenConfig { @@ -51,10 +36,12 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code public static final String DEFAULT_LIBRARY = ""; public static final String DATE_LIBRARY = "dateLibrary"; public static final String JAVA8_MODE = "java8"; + public static final String SUPPORT_ASYNC = "supportAsync"; public static final String WITH_XML = "withXml"; public static final String SUPPORT_JAVA6 = "supportJava6"; protected String dateLibrary = "threetenbp"; + protected boolean supportAsync = false; protected boolean java8Mode = false; protected boolean withXml = false; protected String invokerPackage = "io.swagger"; @@ -81,10 +68,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code protected String javaUtilPrefix = ""; protected Boolean serializableModel = false; protected boolean serializeBigDecimalAsString = false; - protected boolean hideGenerationTimestamp = false; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; - protected boolean supportJava6= false; + protected boolean supportJava6 = false; public AbstractJavaCodegen() { super(); @@ -95,23 +81,25 @@ public AbstractJavaCodegen() { modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); + hideGenerationTimestamp = false; + setReservedWordsLowerCase( - Arrays.asList( - // used as internal variables, can collide with parameter names - "localVarPath", "localVarQueryParams", "localVarCollectionQueryParams", - "localVarHeaderParams", "localVarFormParams", "localVarPostBody", - "localVarAccepts", "localVarAccept", "localVarContentTypes", - "localVarContentType", "localVarAuthNames", "localReturnType", - "ApiClient", "ApiException", "ApiResponse", "Configuration", "StringUtil", - - // language reserved words - "abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while", "null") + Arrays.asList( + // used as internal variables, can collide with parameter names + "localVarPath", "localVarQueryParams", "localVarCollectionQueryParams", + "localVarHeaderParams", "localVarFormParams", "localVarPostBody", + "localVarAccepts", "localVarAccept", "localVarContentTypes", + "localVarContentType", "localVarAuthNames", "localReturnType", + "ApiClient", "ApiException", "ApiResponse", "Configuration", "StringUtil", + + // language reserved words + "abstract", "continue", "for", "new", "switch", "assert", + "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", "byte", "else", + "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", + "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", + "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", + "native", "super", "while", "null") ); languageSpecificPrimitives = new HashSet( @@ -190,13 +178,13 @@ public void processOpts() { this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); } else if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { // guess from api package - String derviedInvokerPackage = deriveInvokerPackageName((String)additionalProperties.get(CodegenConstants.API_PACKAGE)); + String derviedInvokerPackage = deriveInvokerPackageName((String) additionalProperties.get(CodegenConstants.API_PACKAGE)); this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derviedInvokerPackage); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); LOGGER.info("Invoker Package Name, originally not set, is now dervied from api package name: " + derviedInvokerPackage); } else if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { // guess from model package - String derviedInvokerPackage = deriveInvokerPackageName((String)additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); + String derviedInvokerPackage = deriveInvokerPackageName((String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derviedInvokerPackage); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); LOGGER.info("Invoker Package Name, originally not set, is now dervied from model package name: " + derviedInvokerPackage); @@ -205,6 +193,14 @@ public void processOpts() { additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); } + if (!additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { + additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); + } + + if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); + } + if (additionalProperties.containsKey(CodegenConstants.GROUP_ID)) { this.setGroupId((String) additionalProperties.get(CodegenConstants.GROUP_ID)); } else { @@ -308,7 +304,7 @@ public void processOpts() { this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); } - if(additionalProperties.containsKey(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING)) { + if (additionalProperties.containsKey(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING)) { this.setSerializeBigDecimalAsString(Boolean.valueOf(additionalProperties.get(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING).toString())); } @@ -381,16 +377,23 @@ public void processOpts() { // used later in recursive import in postProcessingModels importMapping.put("com.fasterxml.jackson.annotation.JsonProperty", "com.fasterxml.jackson.annotation.JsonCreator"); - if(additionalProperties.containsKey(JAVA8_MODE)) { + if (additionalProperties.containsKey(JAVA8_MODE)) { setJava8Mode(Boolean.parseBoolean(additionalProperties.get(JAVA8_MODE).toString())); - if ( java8Mode ) { + if (java8Mode) { additionalProperties.put("java8", "true"); } } - if(additionalProperties.containsKey(WITH_XML)) { + if (additionalProperties.containsKey(SUPPORT_ASYNC)) { + setSupportAsync(Boolean.parseBoolean(additionalProperties.get(SUPPORT_ASYNC).toString())); + if (supportAsync) { + additionalProperties.put(SUPPORT_ASYNC, "true"); + } + } + + if (additionalProperties.containsKey(WITH_XML)) { setWithXml(Boolean.parseBoolean(additionalProperties.get(WITH_XML).toString())); - if ( withXml ) { + if (withXml) { additionalProperties.put(WITH_XML, "true"); } } @@ -451,7 +454,7 @@ private void sanitizeConfig() { @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -519,8 +522,8 @@ public String toVarName(String name) { return "propertyClass"; } - if("_".equals(name)) { - name = "_u"; + if ("_".equals(name)) { + name = "_u"; } // if it's all uppper case, do nothing @@ -528,7 +531,7 @@ public String toVarName(String name) { return name; } - if(startsWithTwoUppercaseLetters(name)){ + if (startsWithTwoUppercaseLetters(name)) { name = name.substring(0, 2).toLowerCase() + name.substring(2); } @@ -546,7 +549,7 @@ public String toVarName(String name) { private boolean startsWithTwoUppercaseLetters(String name) { boolean startsWithTwoUppercaseLetters = false; - if(name.length() > 1) { + if (name.length() > 1) { startsWithTwoUppercaseLetters = name.substring(0, 2).equals(name.substring(0, 2).toUpperCase()); } return startsWithTwoUppercaseLetters; @@ -612,25 +615,22 @@ public String toModelFilename(String name) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); if (inner == null) { - LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined"); - // TODO maybe better defaulting to StringProperty than returning null - return null; + LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined.Default to string"); + inner = new StringSchema().description("TODO default missing array inner type to string"); } - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); if (inner == null) { - LOGGER.warn(mp.getName() + "(map property) does not have a proper inner type defined"); - // TODO maybe better defaulting to StringProperty than returning null - return null; + LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string"); + inner = new StringSchema().description("TODO default missing array inner type to string"); } - return getSwaggerType(p) + ""; + return getSchemaType(p) + ""; } return super.getTypeDeclaration(p); } @@ -644,9 +644,9 @@ public String getAlias(String name) { } @Override - public String toDefaultValue(Property p) { - if (p instanceof ArrayProperty) { - final ArrayProperty ap = (ArrayProperty) p; + public String toDefaultValue(Schema p) { + if (ModelUtils.isArraySchema(p)) { + final ArraySchema ap = (ArraySchema) p; final String pattern; if (fullJavaUtil) { pattern = "new java.util.ArrayList<%s>()"; @@ -667,19 +667,18 @@ public String toDefaultValue(Property p) { } return String.format(pattern, typeDeclaration); - } else if (p instanceof MapProperty) { - final MapProperty ap = (MapProperty) p; + } else if (ModelUtils.isMapSchema(p)) { final String pattern; if (fullJavaUtil) { pattern = "new java.util.HashMap<%s>()"; } else { pattern = "new HashMap<%s>()"; } - if (ap.getAdditionalProperties() == null) { + if (p.getAdditionalProperties() == null) { return null; } - String typeDeclaration = String.format("String, %s", getTypeDeclaration(ap.getAdditionalProperties())); + String typeDeclaration = String.format("String, %s", getTypeDeclaration((Schema) p.getAdditionalProperties())); Object java8obj = additionalProperties.get("java8"); if (java8obj != null) { Boolean java8 = Boolean.valueOf(java8obj.toString()); @@ -689,41 +688,33 @@ public String toDefaultValue(Property p) { } return String.format(pattern, typeDeclaration); - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "null"; - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString()+"l"; - } - return "null"; - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString() + "d"; + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) { + return p.getDefault().toString() + "l"; + } else { + return p.getDefault().toString(); + } } return "null"; - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString() + "f"; + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + if (SchemaTypeUtil.FLOAT_FORMAT.equals(p.getFormat())) { + return p.getDefault().toString() + "f"; + } else { + return p.getDefault().toString() + "d"; + } } return "null"; - } else if (p instanceof BooleanProperty) { - BooleanProperty bp = (BooleanProperty) p; - if (bp.getDefault() != null) { - return bp.getDefault().toString(); + } else if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } return "null"; - } else if (p instanceof StringProperty) { - StringProperty sp = (StringProperty) p; - if (sp.getDefault() != null) { - String _default = sp.getDefault(); - if (sp.getEnum() == null) { + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + String _default = (String) p.getDefault(); + if (p.getEnum() == null) { return "\"" + escapeText(_default) + "\""; } else { // convert to enum var name later in postProcessModels @@ -800,8 +791,8 @@ public void setParameterExampleValue(CodegenParameter p) { } @Override - public String toExampleValue(Property p) { - if(p.getExample() != null) { + public String toExampleValue(Schema p) { + if (p.getExample() != null) { return escapeText(p.getExample().toString()); } else { return super.toExampleValue(p); @@ -809,8 +800,8 @@ public String toExampleValue(Property p) { } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String swaggerType = super.getSchemaType(p); swaggerType = getAlias(swaggerType); @@ -820,7 +811,7 @@ public String getSwaggerType(Property p) { } if (null == swaggerType) { - LOGGER.error("No Type defined for Property " + p); + LOGGER.error("No Type defined for Schema " + p); } return toModelName(swaggerType); } @@ -845,9 +836,9 @@ public String toOperationId(String operationId) { } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); - if(codegenModel.description != null) { + if (codegenModel.description != null) { codegenModel.imports.add("ApiModel"); } if (codegenModel.discriminator != null && additionalProperties.containsKey("jackson")) { @@ -855,7 +846,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe codegenModel.imports.add("JsonTypeInfo"); } if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { - final Model parentModel = allDefinitions.get(codegenModel.parentSchema); + final Schema parentModel = allDefinitions.get(codegenModel.parentSchema); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); } @@ -864,7 +855,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { - if(serializeBigDecimalAsString) { + if (serializeBigDecimalAsString) { if (property.baseType.equals("BigDecimal")) { // we serialize BigDecimal as `string` to avoid precision loss property.vendorExtensions.put("extraAnnotation", "@JsonSerialize(using = ToStringSerializer.class)"); @@ -883,7 +874,7 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } } - if(!BooleanUtils.toBoolean(model.isEnum)) { + if (!BooleanUtils.toBoolean(model.isEnum)) { // needed by all pojos, but not enums model.imports.add("ApiModelProperty"); model.imports.add("ApiModel"); @@ -891,7 +882,8 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } @Override - public void postProcessParameter(CodegenParameter parameter) { } + public void postProcessParameter(CodegenParameter parameter) { + } @Override public Map postProcessModels(Map objs) { @@ -906,7 +898,7 @@ public Map postProcessModels(Map objs) { // if the import package happens to be found in the importMapping (key) // add the corresponding import package to the list if (importMapping.containsKey(_import)) { - Map newImportMap= new HashMap(); + Map newImportMap = new HashMap(); newImportMap.put("import", importMapping.get(_import)); listIterator.add(newImportMap); } @@ -921,61 +913,54 @@ public Map postProcessOperations(Map objs) { // imported in the template already. List> imports = (List>) objs.get("imports"); Pattern pattern = Pattern.compile("java\\.util\\.(List|ArrayList|Map|HashMap)"); - for (Iterator> itr = imports.iterator(); itr.hasNext();) { + for (Iterator> itr = imports.iterator(); itr.hasNext(); ) { String _import = itr.next().get("import"); if (pattern.matcher(_import).matches()) { - itr.remove(); + itr.remove(); } } return objs; } @Override - public void preprocessSwagger(Swagger swagger) { - if (swagger == null || swagger.getPaths() == null){ + public void preprocessOpenAPI(OpenAPI openAPI) { + if (openAPI == null || openAPI.getPaths() == null) { return; } - for (String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if (path.getOperations() == null){ + for (String pathname : openAPI.getPaths().keySet()) { + PathItem path = openAPI.getPaths().get(pathname); + if (path.readOperations() == null) { continue; } - for (Operation operation : path.getOperations()) { - boolean hasFormParameters = false; - boolean hasBodyParameters = false; - for (Parameter parameter : operation.getParameters()) { - if (parameter instanceof FormParameter) { - hasFormParameters = true; - } - if (parameter instanceof BodyParameter) { - hasBodyParameters = true; - } - } - if (hasBodyParameters || hasFormParameters){ - String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json"; - String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty() ? defaultContentType : operation.getConsumes().get(0); - operation.setVendorExtension("x-contentType", contentType); + for (Operation operation : path.readOperations()) { + if (hasBodyParameter(operation) || hasFormParameter(operation)) { + String defaultContentType = hasFormParameter(operation) ? "application/x-www-form-urlencoded" : "application/json"; + List consumes = new ArrayList(getConsumesInfo(operation)); + String contentType = consumes == null || consumes.isEmpty() ? defaultContentType : consumes.get(0); + operation.addExtension("x-contentType", contentType); } String accepts = getAccept(operation); - operation.setVendorExtension("x-accepts", accepts); + operation.addExtension("x-accepts", accepts); + } } } - private static String getAccept(Operation operation) { + protected static String getAccept(Operation operation) { String accepts = null; String defaultContentType = "application/json"; - if (operation.getProduces() != null && !operation.getProduces().isEmpty()) { + ArrayList produces = new ArrayList(getProducesInfo(operation)); + if (produces != null && !produces.isEmpty()) { StringBuilder sb = new StringBuilder(); - for (String produces : operation.getProduces()) { - if (defaultContentType.equalsIgnoreCase(produces)) { + for (String produce : produces) { + if (defaultContentType.equalsIgnoreCase(produce)) { accepts = defaultContentType; break; } else { if (sb.length() > 0) { sb.append(","); } - sb.append(produces); + sb.append(produce); } } if (accepts == null) { @@ -992,15 +977,6 @@ private static String getAccept(Operation operation) { protected boolean needToImport(String type) { return super.needToImport(type) && type.indexOf(".") < 0; } -/* - @Override - public String findCommonPrefixOfVars(List vars) { - String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()])); - // exclude trailing characters that should be part of a valid variable - // e.g. ["status-on", "status-off"] => "status-" (not "status-o") - return prefix.replaceAll("[a-zA-Z0-9]+\\z", ""); - } -*/ @Override public String toEnumName(CodegenProperty property) { @@ -1020,7 +996,7 @@ public String toEnumVarName(String value, String datatype) { // number if ("Integer".equals(datatype) || "Long".equals(datatype) || - "Float".equals(datatype) || "Double".equals(datatype)) { + "Float".equals(datatype) || "Double".equals(datatype)) { String varName = "NUMBER_" + value; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); @@ -1053,8 +1029,8 @@ public String toEnumValue(String value, String datatype) { } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, OpenAPI openAPI) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, openAPI); op.path = sanitizePath(op.path); return op; } @@ -1067,7 +1043,7 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code // Because the child models extend the parents, the enums will be available via the parent. // Only bother with reconciliation if the parent model has enums. - if (!parentCodegenModel.hasEnums) { + if (!parentCodegenModel.hasEnums) { return codegenModel; } @@ -1095,10 +1071,10 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code } } - if(removedChildEnum) { + if (removedChildEnum) { // If we removed an entry from this model's vars, we need to ensure hasMore is updated int count = 0, numVars = codegenProperties.size(); - for(CodegenProperty codegenProperty : codegenProperties) { + for (CodegenProperty codegenProperty : codegenProperties) { count += 1; codegenProperty.hasMore = (count < numVars) ? true : false; } @@ -1110,12 +1086,16 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code private static String sanitizePackageName(String packageName) { packageName = packageName.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_"); - if(Strings.isNullOrEmpty(packageName)) { + if (Strings.isNullOrEmpty(packageName)) { return "invalidPackageName"; } return packageName; } + public String getInvokerPackage() { + return invokerPackage; + } + public void setInvokerPackage(String invokerPackage) { this.invokerPackage = invokerPackage; } @@ -1217,6 +1197,10 @@ public void setJava8Mode(boolean enabled) { this.java8Mode = enabled; } + public void setSupportAsync(boolean enabled) { + this.supportAsync = enabled; + } + @Override public String escapeQuotationMark(String input) { // remove " to avoid code injection @@ -1240,7 +1224,7 @@ private String deriveInvokerPackageName(String input) { StringBuilder sb = new StringBuilder(); String delim = ""; - for (String p : Arrays.copyOf(parts, parts.length-1)) { + for (String p : Arrays.copyOf(parts, parts.length - 1)) { sb.append(delim).append(p); delim = "."; } @@ -1261,7 +1245,7 @@ public boolean convertPropertyToBoolean(String propertyKey) { booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString()); } - return booleanValue; + return booleanValue; } public void writePropertyBack(String propertyKey, boolean value) { 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 f408dd59af66..0681e18ab923 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 @@ -1,5 +1,6 @@ package org.openapitools.codegen.languages; +import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -9,17 +10,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenParameter; -import org.openapitools.codegen.CodegenResponse; -import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.*; import org.openapitools.codegen.languages.features.BeanValidationFeatures; -import org.openapitools.codegen.languages.features.UseGenericResponseFeatures; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.Swagger; +import org.openapitools.codegen.utils.ModelUtils; +import org.openapitools.codegen.utils.URLPathUtils; +import io.swagger.v3.oas.models.*; public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen implements BeanValidationFeatures { /** @@ -86,45 +81,45 @@ public void processOpts() { } @Override - public void preprocessSwagger(Swagger swagger) { - if ( "/".equals(swagger.getBasePath()) ) { + public void preprocessOpenAPI(OpenAPI openAPI) { + /* TODO there should be no need for the following logic + if ("/".equals(swagger.getBasePath())) { swagger.setBasePath(""); } + */ if (!this.additionalProperties.containsKey("serverPort")) { - final String host = swagger.getHost(); - String port = "8080"; // Default value for a JEE Server - if ( host != null ) { - String[] parts = host.split(":"); - if ( parts.length > 1 ) { - port = parts[1]; - } + URL url = URLPathUtils.getServerURL(openAPI); + + Integer port = 8080; // Default value for a JEE Server + if (url.getPort() != 0) { + port = url.getPort(); } this.additionalProperties.put("serverPort", port); } - if ( swagger.getPaths() != null ) { - for ( String pathname : swagger.getPaths().keySet() ) { - Path path = swagger.getPath(pathname); - if ( path.getOperations() != null ) { - for ( Operation operation : path.getOperations() ) { - if ( operation.getTags() != null ) { + if (openAPI.getPaths() != null) { + for (String pathname : openAPI.getPaths().keySet()) { + PathItem path = openAPI.getPaths().get(pathname); + if (path.readOperations() != null) { + for (Operation operation : path.readOperations()) { + if (operation.getTags() != null) { List> tags = new ArrayList>(); - for ( String tag : operation.getTags() ) { + for (String tag : operation.getTags()) { Map value = new HashMap(); value.put("tag", tag); value.put("hasMore", "true"); tags.add(value); } - if ( tags.size() > 0 ) { + if (tags.size() > 0) { tags.get(tags.size() - 1).remove("hasMore"); } - if ( operation.getTags().size() > 0 ) { + if (operation.getTags().size() > 0) { String tag = operation.getTags().get(0); operation.setTags(Arrays.asList(tag)); } - operation.setVendorExtension("x-tags", tags); + operation.addExtension("x-tags", tags); } } } @@ -134,12 +129,16 @@ public void preprocessSwagger(Swagger swagger) { @Override public Map postProcessOperations(Map objs) { + return jaxrsPostProcessOperations(objs); + } + + static Map jaxrsPostProcessOperations(Map objs) { @SuppressWarnings("unchecked") Map operations = (Map) objs.get("operations"); - if ( operations != null ) { + if (operations != null) { @SuppressWarnings("unchecked") List ops = (List) operations.get("operation"); - for ( CodegenOperation operation : ops ) { + for (CodegenOperation operation : ops) { if (operation.hasConsumes == Boolean.TRUE) { Map firstType = operation.consumes.get(0); if (firstType != null) { @@ -151,27 +150,27 @@ public Map postProcessOperations(Map objs) { boolean isMultipartPost = false; List> consumes = operation.consumes; - if(consumes != null) { - for(Map consume : consumes) { + if (consumes != null) { + for (Map consume : consumes) { String mt = consume.get("mediaType"); - if(mt != null) { - if(mt.startsWith("multipart/form-data")) { + if (mt != null) { + if (mt.startsWith("multipart/form-data")) { isMultipartPost = true; } } } } - for(CodegenParameter parameter : operation.allParams) { - if(isMultipartPost) { + for (CodegenParameter parameter : operation.allParams) { + if (isMultipartPost) { parameter.vendorExtensions.put("x-multipart", "true"); } } List responses = operation.responses; - if ( responses != null ) { - for ( CodegenResponse resp : responses ) { - if ( "0".equals(resp.code) ) { + if (responses != null) { + for (CodegenResponse resp : responses) { + if ("0".equals(resp.code)) { resp.code = "200"; } @@ -190,7 +189,7 @@ public Map postProcessOperations(Map objs) { } } - if ( operation.returnBaseType == null ) { + if (operation.returnBaseType == null) { operation.returnType = "void"; operation.returnBaseType = "Void"; // set vendorExtensions.x-java-is-response-void to true as returnBaseType is set to "Void" @@ -210,7 +209,7 @@ public Map postProcessOperations(Map objs) { @Override public String toApiName(final String name) { String computed = name; - if ( computed.length() == 0 ) { + if (computed.length() == 0) { return "DefaultApi"; } computed = sanitizeName(computed); @@ -221,15 +220,15 @@ public String toApiName(final String name) { public String apiFilename(String templateName, String tag) { String result = super.apiFilename(templateName, tag); - if ( templateName.endsWith("Impl.mustache") ) { + if (templateName.endsWith("Impl.mustache")) { int ix = result.lastIndexOf('/'); result = result.substring(0, ix) + "/impl" + result.substring(ix, result.length() - 5) + "ServiceImpl.java"; result = result.replace(apiFileFolder(), implFileFolder(implFolder)); - } else if ( templateName.endsWith("Factory.mustache") ) { + } else if (templateName.endsWith("Factory.mustache")) { int ix = result.lastIndexOf('/'); result = result.substring(0, ix) + "/factories" + result.substring(ix, result.length() - 5) + "ServiceFactory.java"; result = result.replace(apiFileFolder(), implFileFolder(implFolder)); - } else if ( templateName.endsWith("Service.mustache") ) { + } else if (templateName.endsWith("Service.mustache")) { int ix = result.lastIndexOf('.'); result = result.substring(0, ix) + "Service.java"; } 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 9068bba174e0..dcb321d6e6e3 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 @@ -4,9 +4,12 @@ import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.DefaultCodegen; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -181,22 +184,6 @@ public AbstractKotlinCodegen() { cliOptions.add(enumPropertyNamingOpt.defaultValue(enumPropertyNaming.name())); } - protected void addOption(String key, String description) { - addOption(key, description, null); - } - - protected void addOption(String key, String description, String defaultValue) { - CliOption option = new CliOption(key, description); - if (defaultValue != null) option.defaultValue(defaultValue); - cliOptions.add(option); - } - - protected void addSwitch(String key, String description, Boolean defaultValue) { - CliOption option = CliOption.newBoolean(key, description); - if (defaultValue != null) option.defaultValue(defaultValue.toString()); - cliOptions.add(option); - } - @Override public String apiDocFileFolder() { return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); @@ -252,17 +239,17 @@ public void setEnumPropertyNaming(final String enumPropertyNamingType) { * @return string presentation of the type **/ @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type; // This maps, for example, long -> kotlin.Long based on hashes in this type's constructor - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) { return toModelName(type); } } else { - type = swaggerType; + type = openAPIType; } return toModelName(type); } @@ -274,15 +261,14 @@ public String getSwaggerType(Property p) { * @return a string presentation of the property type */ @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - return getArrayTypeDeclaration((ArrayProperty) p); - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + return getArrayTypeDeclaration((ArraySchema) p); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); // Maps will be keyed only by primitive Kotlin string - return getSwaggerType(p) + ""; + return getSchemaType(p) + ""; } return super.getTypeDeclaration(p); } @@ -423,9 +409,9 @@ public String toEnumVarName(String value, String datatype) { } @Override - public String toInstantiationType(Property p) { - if (p instanceof ArrayProperty) { - return getArrayTypeDeclaration((ArrayProperty) p); + public String toInstantiationType(Schema p) { + if (ModelUtils.isArraySchema(p)) { + return getArrayTypeDeclaration((ArraySchema) p); } return super.toInstantiationType(p); } @@ -479,15 +465,15 @@ public String toModelName(final String name) { /** * Provides a strongly typed declaration for simple arrays of some type and arrays of arrays of some type. * - * @param arr - * @return + * @param arr Array schema + * @return type declaration of array */ - private String getArrayTypeDeclaration(ArrayProperty arr) { + private String getArrayTypeDeclaration(ArraySchema arr) { // TODO: collection type here should be fully qualified namespace to avoid model conflicts // This supports arrays of arrays. String arrayType = typeMapping.get("array"); StringBuilder instantiationType = new StringBuilder(arrayType); - Property items = arr.getItems(); + Schema items = arr.getItems(); String nestedType = getTypeDeclaration(items); // TODO: We may want to differentiate here between generics and primitive arrays. instantiationType.append("<").append(nestedType).append(">"); 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 9b8aae08b96c..b60280c36478 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 @@ -9,7 +9,11 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.*; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import java.io.File; import java.util.Arrays; @@ -44,7 +48,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg protected String docsBasePath = "docs"; protected String apiDirName = "Api"; protected String modelDirName = "Model"; - protected String variableNamingConvention= "snake_case"; + protected String variableNamingConvention = "snake_case"; protected String apiDocPath = docsBasePath + File.separator + apiDirName; protected String modelDocPath = docsBasePath + File.separator + modelDirName; @@ -62,12 +66,12 @@ public AbstractPhpCodegen() { setReservedWordsLowerCase( Arrays.asList( - // local variables used in api methods (endpoints) - "resourcePath", "httpBody", "queryParams", "headerParams", - "formParams", "_header_accept", "_tempBody", + // local variables used in api methods (endpoints) + "resourcePath", "httpBody", "queryParams", "headerParams", + "formParams", "_header_accept", "_tempBody", - // PHP reserved words - "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") + // PHP reserved words + "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") ); // ref: http://php.net/manual/en/language.types.intro.php @@ -248,12 +252,12 @@ public String toSrcPath(String packageName, String basePath) { // Trim prefix file separators from package path .replaceAll(regFirstPathSeparator, "")) // Trim trailing file separators from the overall path - .replaceAll(regLastPathSeparator+ "$", ""); + .replaceAll(regLastPathSeparator + "$", ""); } - @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + @Override + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -300,16 +304,15 @@ public String toApiDocFilename(String name) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return getTypeDeclaration(inner) + "[]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; - } else if (p instanceof RefProperty) { + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } else if (!StringUtils.isEmpty(p.get$ref())) { // model String type = super.getTypeDeclaration(p); return (!languageSpecificPrimitives.contains(type)) ? "\\" + modelPackage + "\\" + type : type; @@ -326,18 +329,18 @@ public String getTypeDeclaration(String name) { } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) { return type; } else if (instantiationTypes.containsKey(type)) { return type; } } else { - type = swaggerType; + type = openAPIType; } if (type == null) { return null; @@ -345,6 +348,10 @@ public String getSwaggerType(Property p) { return toModelName(type); } + public String getInvokerPackage() { + return invokerPackage; + } + public void setInvokerPackage(String invokerPackage) { this.invokerPackage = invokerPackage; } @@ -379,13 +386,13 @@ public String toVarName(String name) { name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. if ("camelCase".equals(variableNamingConvention)) { - // return the name in camelCase style - // phone_number => phoneNumber - name = camelize(name, true); + // return the name in camelCase style + // phone_number => phoneNumber + name = camelize(name, true); } else { // default to snake case - // return the name in underscore style - // PhoneNumber => phone_number - name = underscore(name); + // return the name in underscore style + // PhoneNumber => phone_number + name = underscore(name); } // parameter name starting with number won't compile @@ -471,40 +478,26 @@ public String toOperationId(String operationId) { * @return string presentation of the default value of the property */ @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - return "'" + dp.getDefault() + "'"; - } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { // TODO - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { // TODO - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return "'" + p.getDefault() + "'"; } } 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 ce7623fc82bf..153ffb713faf 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 @@ -11,17 +11,11 @@ import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.DefaultCodegen; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; + import org.apache.commons.lang3.StringUtils; public abstract class AbstractScalaCodegen extends DefaultCodegen { @@ -133,13 +127,14 @@ public String escapeReservedWord(String name) { @Override public Mustache.Compiler processCompiler(Mustache.Compiler compiler) { Mustache.Escaper SCALA = new Mustache.Escaper() { - @Override public String escape (String text) { + @Override + public String escape(String text) { // Fix included as suggested by akkie in #6393 // The given text is a reserved word which is escaped by enclosing it with grave accents. If we would // escape that with the default Mustache `HTML` escaper, then the escaper would also escape our grave // accents. So we remove the grave accents before the escaping and add it back after the escaping. if (text.startsWith("`") && text.endsWith("`")) { - String unescaped = text.substring(1, text.length() - 1); + String unescaped = text.substring(1, text.length() - 1); return "`" + Escapers.HTML.escape(unescaped) + "`"; } @@ -162,23 +157,22 @@ public String modelFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String swaggerType = super.getSchemaType(p); String type = null; if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); @@ -192,14 +186,13 @@ public String getSwaggerType(Property p) { } @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); + public String toInstantiationType(Schema p) { + if (ModelUtils.isMapSchema(p)) { + String inner = getSchemaType((Schema) p.getAdditionalProperties()); return instantiationTypes.get("map") + "[String, " + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); return instantiationTypes.get("array") + "[" + inner + "]"; } else { return null; @@ -207,31 +200,26 @@ public String toInstantiationType(Property p) { } @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "null"; - } else if (p instanceof BooleanProperty) { - return "null"; - } else if (p instanceof DateProperty) { + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { return "null"; - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateSchema(p)) { return "null"; - } else if (p instanceof DoubleProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { return "null"; - } else if (p instanceof FloatProperty) { + } else if (ModelUtils.isNumberSchema(p)) { return "null"; - } else if (p instanceof IntegerProperty) { + } else if (ModelUtils.isIntegerSchema(p)) { return "null"; - } else if (p instanceof LongProperty) { - return "null"; - } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); + } else if (ModelUtils.isMapSchema(p)) { + String inner = getSchemaType((Schema) p.getAdditionalProperties()); return "new HashMap[String, " + inner + "]() "; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); return "new ListBuffer[" + inner + "]() "; + } else if (ModelUtils.isStringSchema(p)) { + return "null"; } else { return "null"; } 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 f6e885f699fd..3477ca22e0e4 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 @@ -1,8 +1,5 @@ package org.openapitools.codegen.languages; -import io.swagger.models.parameters.Parameter; -import org.apache.commons.lang3.StringUtils; - import java.io.File; import java.util.*; @@ -13,24 +10,22 @@ import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FileProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.oas.models.info.*; +import io.swagger.v3.parser.util.SchemaTypeUtil; + +import org.apache.commons.lang3.StringUtils; public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value"; private static final String UNDEFINED_VALUE = "undefined"; - protected String modelPropertyNaming= "camelCase"; + protected String modelPropertyNaming = "camelCase"; protected Boolean supportsES6 = true; protected HashSet languageGenericTypes; @@ -66,7 +61,7 @@ public AbstractTypeScriptClientCodegen() { "File", "Error", "Map" - )); + )); languageGenericTypes = new HashSet(Arrays.asList( "Array" @@ -126,7 +121,7 @@ public CodegenType getTag() { @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -153,7 +148,7 @@ public String toVarName(String name) { // sanitize name name = sanitizeName(name); - if("_".equals(name)) { + if ("_".equals(name)) { name = "_u"; } @@ -216,77 +211,63 @@ public String toModelFilename(String name) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return "{ [key: string]: "+ getTypeDeclaration(inner) + "; }"; - } else if (p instanceof FileProperty) { + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return "{ [key: string]: " + getTypeDeclaration(inner) + "; }"; + } else if (ModelUtils.isFileSchema(p)) { + return "any"; + } else if (ModelUtils.isBinarySchema(p)) { return "any"; } return super.getTypeDeclaration(p); } - @Override - protected String getParameterDataType(Parameter parameter, Property p) { + protected String getParameterDataType(Parameter parameter, Schema p) { // handle enums of various data types - Property inner; - if (p instanceof ArrayProperty) { - ArrayProperty mp1 = (ArrayProperty) p; + Schema inner; + if (ModelUtils.isArraySchema(p)) { + ArraySchema mp1 = (ArraySchema) p; inner = mp1.getItems(); - return this.getSwaggerType(p) + "<" + this.getParameterDataType(parameter, inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - inner = mp.getAdditionalProperties(); + return this.getSchemaType(p) + "<" + this.getParameterDataType(parameter, inner) + ">"; + } else if (ModelUtils.isMapSchema(p)) { + inner = (Schema) p.getAdditionalProperties(); return "{ [key: string]: " + this.getParameterDataType(parameter, inner) + "; }"; - } else if (p instanceof StringProperty) { + } else if (ModelUtils.isStringSchema(p)) { // Handle string enums - StringProperty sp = (StringProperty) p; - if (sp.getEnum() != null) { - return enumValuesToEnumTypeUnion(sp.getEnum(), "string"); + if (p.getEnum() != null) { + return enumValuesToEnumTypeUnion(p.getEnum(), "string"); } - } else if (p instanceof IntegerProperty) { + } else if (ModelUtils.isIntegerSchema(p)) { // Handle integer enums - IntegerProperty sp = (IntegerProperty) p; - if (sp.getEnum() != null) { - return numericEnumValuesToEnumTypeUnion(new ArrayList(sp.getEnum())); - } - } else if (p instanceof LongProperty) { - // Handle long enums - LongProperty sp = (LongProperty) p; - if (sp.getEnum() != null) { - return numericEnumValuesToEnumTypeUnion(new ArrayList(sp.getEnum())); + if (p.getEnum() != null) { + return numericEnumValuesToEnumTypeUnion(new ArrayList(p.getEnum())); } - } else if (p instanceof DoubleProperty) { + } else if (ModelUtils.isNumberSchema(p)) { // Handle double enums - DoubleProperty sp = (DoubleProperty) p; - if (sp.getEnum() != null) { - return numericEnumValuesToEnumTypeUnion(new ArrayList(sp.getEnum())); - } - } else if (p instanceof FloatProperty) { - // Handle float enums - FloatProperty sp = (FloatProperty) p; - if (sp.getEnum() != null) { - return numericEnumValuesToEnumTypeUnion(new ArrayList(sp.getEnum())); + if (p.getEnum() != null) { + return numericEnumValuesToEnumTypeUnion(new ArrayList(p.getEnum())); } - } else if (p instanceof DateProperty) { + } + /* TODO revise the logic below + else if (ModelUtils.isDateSchema(p)) { // Handle date enums - DateProperty sp = (DateProperty) p; + DateSchema sp = (DateSchema) p; if (sp.getEnum() != null) { return enumValuesToEnumTypeUnion(sp.getEnum(), "string"); } - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { // Handle datetime enums - DateTimeProperty sp = (DateTimeProperty) p; + DateTimeSchema sp = (DateTimeSchema) p; if (sp.getEnum() != null) { return enumValuesToEnumTypeUnion(sp.getEnum(), "string"); } - } + }*/ return this.getTypeDeclaration(p); } @@ -294,14 +275,14 @@ protected String getParameterDataType(Parameter parameter, Property p) { * Converts a list of strings to a literal union for representing enum values as a type. * Example output: 'available' | 'pending' | 'sold' * - * @param values list of allowed enum values + * @param values list of allowed enum values * @param dataType either "string" or "number" - * @return + * @return a literal union for representing enum values as a type */ protected String enumValuesToEnumTypeUnion(List values, String dataType) { StringBuilder b = new StringBuilder(); boolean isFirst = true; - for (String value: values) { + for (String value : values) { if (!isFirst) { b.append(" | "); } @@ -315,70 +296,57 @@ protected String enumValuesToEnumTypeUnion(List values, String dataType) * Converts a list of numbers to a literal union for representing enum values as a type. * Example output: 3 | 9 | 55 * - * @param values - * @return + * @param values a list of numbers + * @return a literal union for representing enum values as a type */ protected String numericEnumValuesToEnumTypeUnion(List values) { List stringValues = new ArrayList<>(); - for (Number value: values) { + for (Number value : values) { stringValues.add(value.toString()); } return enumValuesToEnumTypeUnion(stringValues, "number"); } @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty sp = (StringProperty) p; - if (sp.getDefault() != null) { - return "'" + sp.getDefault() + "'"; - } + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { return UNDEFINED_VALUE; - } else if (p instanceof BooleanProperty) { + } else if (ModelUtils.isDateSchema(p)) { return UNDEFINED_VALUE; - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { return UNDEFINED_VALUE; - } else if (p instanceof DateTimeProperty) { - return UNDEFINED_VALUE; - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; + } else if (ModelUtils.isNumberSchema(p)) { + NumberSchema dp = (NumberSchema) p; if (dp.getDefault() != null) { return dp.getDefault().toString(); } return UNDEFINED_VALUE; - } else if (p instanceof FloatProperty) { - FloatProperty fp = (FloatProperty) p; - if (fp.getDefault() != null) { - return fp.getDefault().toString(); - } - return UNDEFINED_VALUE; - } else if (p instanceof IntegerProperty) { - IntegerProperty ip = (IntegerProperty) p; - if (ip.getDefault() != null) { - return ip.getDefault().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } return UNDEFINED_VALUE; - } else if (p instanceof LongProperty) { - LongProperty lp = (LongProperty) p; - if (lp.getDefault() != null) { - return lp.getDefault().toString(); + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return "'" + (String) p.getDefault() + "'"; } return UNDEFINED_VALUE; } else { return UNDEFINED_VALUE; } + } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) return type; } else - type = swaggerType; + type = openAPIType; return toModelName(type); } @@ -400,12 +368,12 @@ public String toOperationId(String operationId) { public void setModelPropertyNaming(String naming) { if ("original".equals(naming) || "camelCase".equals(naming) || - "PascalCase".equals(naming) || "snake_case".equals(naming)) { + "PascalCase".equals(naming) || "snake_case".equals(naming)) { this.modelPropertyNaming = naming; } else { throw new IllegalArgumentException("Invalid model property naming '" + - naming + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); + naming + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); } } @@ -415,13 +383,18 @@ public String getModelPropertyNaming() { public 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); - default: throw new IllegalArgumentException("Invalid model property naming '" + - name + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); + case original: + return name; + case camelCase: + return camelize(name, true); + case PascalCase: + return camelize(name); + case snake_case: + return underscore(name); + default: + throw new IllegalArgumentException("Invalid model property naming '" + + name + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); } } @@ -506,11 +479,11 @@ public Map postProcessModels(Map objs) { for (CodegenProperty var : cm.allVars) { if (Boolean.TRUE.equals(var.isEnum)) { var.datatypeWithEnum = var.datatypeWithEnum - .replace(var.enumName, cm.classname + "." + var.enumName); + .replace(var.enumName, cm.classname + "." + var.enumName); } } } - } + } return objs; } @@ -526,7 +499,7 @@ public Map postProcessAllModels(Map objs) { CodegenModel cm = (CodegenModel) mo.get("model"); if (cm.discriminator != null && cm.children != null) { for (CodegenModel child : cm.children) { - this.setDiscriminatorValue(child, cm.discriminator, this.getDiscriminatorValue(child)); + this.setDiscriminatorValue(child, cm.discriminator.getPropertyName(), this.getDiscriminatorValue(child)); } } } @@ -558,7 +531,7 @@ private void setDiscriminatorValue(CodegenModel model, String baseName, String v private String getDiscriminatorValue(CodegenModel model) { return model.vendorExtensions.containsKey(X_DISCRIMINATOR_TYPE) ? - (String) model.vendorExtensions.get(X_DISCRIMINATOR_TYPE) : model.classname; + (String) model.vendorExtensions.get(X_DISCRIMINATOR_TYPE) : model.classname; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaCodegen.java index 3df755cee458..5f7a0e715f73 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaCodegen.java @@ -7,6 +7,8 @@ import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.ModelUtils; + public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig { @@ -73,17 +75,17 @@ public void processOpts() { String pkgName = names[0]; additionalProperties.put("packageLevel1", pkgName); supportingFiles.add(new SupportingFile("package-spec-level1.mustache", null, - "src" + File.separator + toFilename(names[0]) + ".ads")); + "src" + File.separator + toFilename(names[0]) + ".ads")); if (names.length > 1) { String fileName = toFilename(names[0]) + "-" + toFilename(names[1]) + ".ads"; pkgName = names[0] + "." + names[1]; additionalProperties.put("packageLevel2", pkgName); supportingFiles.add(new SupportingFile("package-spec-level2.mustache", null, - "src" + File.separator + fileName)); + "src" + File.separator + fileName)); } pkgName = this.modelPackage; supportingFiles.add(new SupportingFile("client.mustache", null, - "src" + File.separator + toFilename(pkgName) + "-client.adb")); + "src" + File.separator + toFilename(pkgName) + "-client.adb")); additionalProperties.put("packageName", toFilename(pkgName)); // add lambda for mustache templates diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaServerCodegen.java index 4d2e43138ce4..b38530500c5d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaServerCodegen.java @@ -7,6 +7,7 @@ import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.ModelUtils; public class AdaServerCodegen extends AbstractAdaCodegen implements CodegenConfig { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AkkaScalaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AkkaScalaClientCodegen.java index 144c87de3a3b..3191751f78cc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AkkaScalaClientCodegen.java @@ -4,6 +4,7 @@ import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; +import io.swagger.v3.oas.models.security.SecurityScheme; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenConstants; @@ -13,18 +14,11 @@ import org.openapitools.codegen.CodegenSecurity; import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.auth.SecuritySchemeDefinition; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; + import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -156,9 +150,9 @@ public String getHelp() { @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); - } + } return "`" + name + "`"; } @@ -195,7 +189,7 @@ public Map postProcessOperations(Map objs) { } @Override - public List fromSecurity(Map schemes) { + public List fromSecurity(Map schemes) { final List codegenSecurities = super.fromSecurity(schemes); if (!removeOAuthSecurities) { return codegenSecurities; @@ -248,34 +242,30 @@ public String toEnumName(CodegenProperty property) { } @Override - public String toDefaultValue(Property p) { - if (!p.getRequired()) { + public String toDefaultValue(Schema p) { + if (p.getRequired() != null && p.getRequired().contains(p.getName())) { return "None"; } - if (p instanceof StringProperty) { - return "null"; - } else if (p instanceof BooleanProperty) { - return "null"; - } else if (p instanceof DateProperty) { - return "null"; - } else if (p instanceof DateTimeProperty) { + + if (ModelUtils.isBooleanSchema(p)) { return "null"; - } else if (p instanceof DoubleProperty) { + } else if (ModelUtils.isDateSchema(p)) { return "null"; - } else if (p instanceof FloatProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { return "null"; - } else if (p instanceof IntegerProperty) { + } else if (ModelUtils.isNumberSchema(p)) { return "null"; - } else if (p instanceof LongProperty) { + } else if (ModelUtils.isIntegerSchema(p)) { return "null"; - } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); + } else if (ModelUtils.isMapSchema(p)) { + String inner = getSchemaType((Schema) p.getAdditionalProperties()); return "Map[String, " + inner + "].empty "; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); return "Seq[" + inner + "].empty "; + } else if (ModelUtils.isStringSchema(p)) { + return "null"; } else { return "null"; } 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 0a9b692214f5..b73860bb3acc 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 @@ -7,9 +7,10 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import java.io.File; import java.util.Arrays; @@ -55,22 +56,22 @@ public AndroidClientCodegen() { setReservedWordsLowerCase( Arrays.asList( - // local variable names used in API methods (endpoints) - "localVarPostBody", "localVarPath", "localVarQueryParams", "localVarHeaderParams", - "localVarFormParams", "localVarContentTypes", "localVarContentType", - "localVarResponse", "localVarBuilder", "authNames", "basePath", "apiInvoker", - - // due to namespace collusion - "Object", - - // android reserved words - "abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while", "null") + // local variable names used in API methods (endpoints) + "localVarPostBody", "localVarPath", "localVarQueryParams", "localVarHeaderParams", + "localVarFormParams", "localVarContentTypes", "localVarContentType", + "localVarResponse", "localVarBuilder", "authNames", "basePath", "apiInvoker", + + // due to namespace collusion + "Object", + + // android reserved words + "abstract", "continue", "for", "new", "switch", "assert", + "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", "byte", "else", + "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", + "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", + "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", + "native", "super", "while", "null") ); languageSpecificPrimitives = new HashSet( @@ -128,8 +129,8 @@ public String getHelp() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -147,52 +148,51 @@ public String modelFileFolder() { @Override public String apiDocFileFolder() { - return (outputFolder + "/" + apiDocPath).replace( '/', File.separatorChar ); + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); } @Override public String modelDocFileFolder() { - return ( outputFolder + "/" + modelDocPath ).replace( '/', File.separatorChar ); + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); } @Override - public String toApiDocFilename( String name ) { - return toApiName( name ); + public String toApiDocFilename(String name) { + return toApiName(name); } @Override - public String toModelDocFilename( String name ) { - return toModelName( name ); + public String toModelDocFilename(String name) { + return toModelName(name); } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + ""; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + + return getSchemaType(p) + ""; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type) || type.indexOf(".") >= 0 || - type.equals("Map") || type.equals("List") || - type.equals("File") || type.equals("Date")) { + type.equals("Map") || type.equals("List") || + type.equals("File") || type.equals("Date")) { return type; } } else { - type = swaggerType; + type = openAPIType; } return toModelName(type); } @@ -364,6 +364,14 @@ public void processOpts() { additionalProperties.put("authPackage", authPackage); } + if (!additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { + additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); + } + + if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); + } + if (additionalProperties.containsKey(CodegenConstants.GROUP_ID)) { this.setGroupId((String) additionalProperties.get(CodegenConstants.GROUP_ID)); } else { @@ -420,8 +428,8 @@ public void processOpts() { additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); //make api and model doc path available in mustache template - additionalProperties.put( "apiDocPath", apiDocPath ); - additionalProperties.put( "modelDocPath", modelDocPath ); + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); if (StringUtils.isEmpty(getLibrary())) { setLibrary("volley"); // set volley as the default library @@ -433,88 +441,8 @@ public void processOpts() { } else if ("httpclient".equals(getLibrary())) { addSupportingFilesForHttpClient(); } else { - throw new IllegalArgumentException("Invalid 'library' option specified: '" + getLibrary() + "'. Must be 'httpclient' or 'volley' (default)"); + throw new IllegalArgumentException("Invalid 'library' option specified: '" + getLibrary() + "'. Must be 'httpclient' or 'volley' (default)"); } - - } - - private void addSupportingFilesForHttpClient() { - // documentation files - modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); - apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); - supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); - supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiInvoker.java")); - supportingFiles.add(new SupportingFile("httpPatch.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "HttpPatch.java")); - supportingFiles.add(new SupportingFile("jsonUtil.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "JsonUtil.java")); - supportingFiles.add(new SupportingFile("apiException.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiException.java")); - supportingFiles.add(new SupportingFile("Pair.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Pair.java")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - - // gradle wrapper files - supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew" )); - supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat" )); - supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties" )); - supportingFiles.add(new SupportingFile( "gradle-wrapper.jar", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar" )); - - } - - private void addSupportingFilesForVolley() { - // documentation files - modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); - apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - // supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); - supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); - supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiInvoker.java")); - supportingFiles.add(new SupportingFile("jsonUtil.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "JsonUtil.java")); - supportingFiles.add(new SupportingFile("apiException.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiException.java")); - supportingFiles.add(new SupportingFile("Pair.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Pair.java")); - supportingFiles.add(new SupportingFile("request/getrequest.mustache", - (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "GetRequest.java")); - supportingFiles.add(new SupportingFile("request/postrequest.mustache", - (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "PostRequest.java")); - supportingFiles.add(new SupportingFile("request/putrequest.mustache", - (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "PutRequest.java")); - supportingFiles.add(new SupportingFile("request/deleterequest.mustache", - (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "DeleteRequest.java")); - supportingFiles.add(new SupportingFile("request/patchrequest.mustache", - (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "PatchRequest.java")); - supportingFiles.add(new SupportingFile("auth/apikeyauth.mustache", - (sourceFolder + File.separator + authPackage).replace(".", File.separator), "ApiKeyAuth.java")); - supportingFiles.add(new SupportingFile("auth/httpbasicauth.mustache", - (sourceFolder + File.separator + authPackage).replace(".", File.separator), "HttpBasicAuth.java")); - supportingFiles.add(new SupportingFile("auth/authentication.mustache", - (sourceFolder + File.separator + authPackage).replace(".", File.separator), "Authentication.java")); - - // gradle wrapper files - supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew" )); - supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat" )); - supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties" )); - supportingFiles.add(new SupportingFile( "gradle-wrapper.jar", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar" )); } public Boolean getUseAndroidMavenGradlePlugin() { @@ -549,6 +477,10 @@ public void setAndroidBuildToolsVersion(String androidBuildToolsVersion) { this.androidBuildToolsVersion = androidBuildToolsVersion; } + public String getInvokerPackage() { + return invokerPackage; + } + public void setInvokerPackage(String invokerPackage) { this.invokerPackage = invokerPackage; } @@ -592,4 +524,83 @@ public String escapeUnsafeCharacters(String input) { return input.replace("*/", "*_/").replace("/*", "/_*"); } + private void addSupportingFilesForVolley() { + // documentation files + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + // supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); + supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiInvoker.java")); + supportingFiles.add(new SupportingFile("jsonUtil.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "JsonUtil.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiException.java")); + supportingFiles.add(new SupportingFile("Pair.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Pair.java")); + supportingFiles.add(new SupportingFile("request/getrequest.mustache", + (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "GetRequest.java")); + supportingFiles.add(new SupportingFile("request/postrequest.mustache", + (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "PostRequest.java")); + supportingFiles.add(new SupportingFile("request/putrequest.mustache", + (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "PutRequest.java")); + supportingFiles.add(new SupportingFile("request/deleterequest.mustache", + (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "DeleteRequest.java")); + supportingFiles.add(new SupportingFile("request/patchrequest.mustache", + (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "PatchRequest.java")); + supportingFiles.add(new SupportingFile("auth/apikeyauth.mustache", + (sourceFolder + File.separator + authPackage).replace(".", File.separator), "ApiKeyAuth.java")); + supportingFiles.add(new SupportingFile("auth/httpbasicauth.mustache", + (sourceFolder + File.separator + authPackage).replace(".", File.separator), "HttpBasicAuth.java")); + supportingFiles.add(new SupportingFile("auth/authentication.mustache", + (sourceFolder + File.separator + authPackage).replace(".", File.separator), "Authentication.java")); + + // gradle wrapper files + supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); + supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); + supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); + supportingFiles.add(new SupportingFile("gradle-wrapper.jar", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar")); + } + + private void addSupportingFilesForHttpClient() { + // documentation files + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); + supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiInvoker.java")); + supportingFiles.add(new SupportingFile("httpPatch.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "HttpPatch.java")); + supportingFiles.add(new SupportingFile("jsonUtil.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "JsonUtil.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiException.java")); + supportingFiles.add(new SupportingFile("Pair.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Pair.java")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + + // gradle wrapper files + supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); + supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); + supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); + supportingFiles.add(new SupportingFile("gradle-wrapper.jar", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar")); + + } + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java index 4a5722e39d26..c65a83e6762a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java @@ -14,93 +14,98 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; + public class Apache2ConfigCodegen extends DefaultCodegen implements CodegenConfig { - public static final String USER_INFO_PATH = "userInfoPath"; - protected String userInfoPath = "/var/www/html/"; - - @Override - public CodegenType getTag() { - return CodegenType.CONFIG; - } - - @Override - public String getName() { - return "apache2"; - } - - @Override - public String getHelp() { - return "Generates an Apache2 Config file with the permissions"; - } - - public Apache2ConfigCodegen() { - super(); - apiTemplateFiles.put("apache-config.mustache", ".conf"); - - embeddedTemplateDir = templateDir = "apache2"; - - cliOptions.add(new CliOption(USER_INFO_PATH, "Path to the user and group files")); - } - - - @Override - public void processOpts() { - if (additionalProperties.containsKey(USER_INFO_PATH)) { - userInfoPath = additionalProperties.get(USER_INFO_PATH).toString(); + public static final String USER_INFO_PATH = "userInfoPath"; + protected String userInfoPath = "/var/www/html/"; + + @Override + public CodegenType getTag() { + return CodegenType.CONFIG; + } + + @Override + public String getName() { + return "apache2"; + } + + @Override + public String getHelp() { + return "Generates an Apache2 Config file with the permissions"; } - } - - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - - @SuppressWarnings("unchecked") - @Override - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - List operationList = (List) operations.get("operation"); - List newOpList = new ArrayList(); - for (CodegenOperation op : operationList) { - String path = new String(op.path); - - String[] items = path.split("/", -1); - List splitPath = new ArrayList(); - for (String item: items) { - if (item.matches("^\\{(.*)\\}$")) { - item = "*"; + + public Apache2ConfigCodegen() { + super(); + apiTemplateFiles.put("apache-config.mustache", ".conf"); + + embeddedTemplateDir = templateDir = "apache2"; + + cliOptions.add(new CliOption(USER_INFO_PATH, "Path to the user and group files")); + } + + + @Override + public void processOpts() { + if (additionalProperties.containsKey(USER_INFO_PATH)) { + userInfoPath = additionalProperties.get(USER_INFO_PATH).toString(); } - splitPath.add(item); - op.path += item + "/"; - } - op.vendorExtensions.put("x-codegen-userInfoPath", userInfoPath); - boolean foundInNewList = false; - for (CodegenOperation op1 : newOpList) { - if (!foundInNewList) { - if (op1.path.equals(op.path)) { - foundInNewList = true; - List currentOtherMethodList = (List) op1.vendorExtensions.get("x-codegen-otherMethods"); - if (currentOtherMethodList == null) { - currentOtherMethodList = new ArrayList(); + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + @SuppressWarnings("unchecked") + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + List newOpList = new ArrayList(); + for (CodegenOperation op : operationList) { + String path = new String(op.path); + + String[] items = path.split("/", -1); + List splitPath = new ArrayList(); + for (String item : items) { + if (item.matches("^\\{(.*)\\}$")) { + item = "*"; + } + splitPath.add(item); + op.path += item + "/"; + } + op.vendorExtensions.put("x-codegen-userInfoPath", userInfoPath); + boolean foundInNewList = false; + for (CodegenOperation op1 : newOpList) { + if (!foundInNewList) { + if (op1.path.equals(op.path)) { + foundInNewList = true; + List currentOtherMethodList = (List) op1.vendorExtensions.get("x-codegen-otherMethods"); + if (currentOtherMethodList == null) { + currentOtherMethodList = new ArrayList(); + } + op.operationIdCamelCase = op1.operationIdCamelCase; + currentOtherMethodList.add(op); + op1.vendorExtensions.put("x-codegen-otherMethods", currentOtherMethodList); + } + } + } + if (!foundInNewList) { + newOpList.add(op); } - op.operationIdCamelCase = op1.operationIdCamelCase; - currentOtherMethodList.add(op); - op1.vendorExtensions.put("x-codegen-otherMethods", currentOtherMethodList); - } } - } - if (!foundInNewList) { - newOpList.add(op); - } + operations.put("operation", newOpList); + return objs; } - operations.put("operation", newOpList); - return objs; - } } 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 7c9cfcbf5f58..2306d7009ca9 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 @@ -1,12 +1,27 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.*; -import io.swagger.models.Info; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.*; +import com.sun.org.apache.xpath.internal.operations.Mod; +import io.swagger.v3.oas.models.responses.ApiResponse; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.info.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.parser.util.SchemaTypeUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -74,29 +89,29 @@ public ApexClientCodegen() { typeMapping.put("UUID", "String"); setReservedWordsLowerCase( - Arrays.asList("abstract", "activate", "and", "any", "array", "as", "asc", "autonomous", - "begin", "bigdecimal", "blob", "break", "bulk", "by", "byte", "case", "cast", - "catch", "char", "class", "collect", "commit", "const", "continue", - "convertcurrency", "date", "decimal", "default", "delete", "desc", "do", "else", - "end", "enum", "exception", "exit", "export", "extends", "false", "final", - "finally", "float", "for", "from", "future", "global", "goto", "group", "having", - "hint", "if", "implements", "import", "inner", "insert", "instanceof", "int", - "interface", "into", "join", "last_90_days", "last_month", "last_n_days", - "last_week", "like", "limit", "list", "long", "loop", "map", "merge", "new", - "next_90_days", "next_month", "next_n_days", "next_week", "not", "null", "nulls", - "number", "object", "of", "on", "or", "outer", "override", "package", "parallel", - "pragma", "private", "protected", "public", "retrieve", "return", "returning", - "rollback", "savepoint", "search", "select", "set", "short", "sort", "stat", - "static", "super", "switch", "synchronized", "system", "testmethod", "then", "this", - "this_month", "this_week", "throw", "today", "tolabel", "tomorrow", "transaction", - "trigger", "true", "try", "type", "undelete", "update", "upsert", "using", - "virtual", "webservice", "when", "where", "while", "yesterday" - )); + Arrays.asList("abstract", "activate", "and", "any", "array", "as", "asc", "autonomous", + "begin", "bigdecimal", "blob", "break", "bulk", "by", "byte", "case", "cast", + "catch", "char", "class", "collect", "commit", "const", "continue", + "convertcurrency", "date", "decimal", "default", "delete", "desc", "do", "else", + "end", "enum", "exception", "exit", "export", "extends", "false", "final", + "finally", "float", "for", "from", "future", "global", "goto", "group", "having", + "hint", "if", "implements", "import", "inner", "insert", "instanceof", "int", + "interface", "into", "join", "last_90_days", "last_month", "last_n_days", + "last_week", "like", "limit", "list", "long", "loop", "map", "merge", "new", + "next_90_days", "next_month", "next_n_days", "next_week", "not", "null", "nulls", + "number", "object", "of", "on", "or", "outer", "override", "package", "parallel", + "pragma", "private", "protected", "public", "retrieve", "return", "returning", + "rollback", "savepoint", "search", "select", "set", "short", "sort", "stat", + "static", "super", "switch", "synchronized", "system", "testmethod", "then", "this", + "this_month", "this_week", "throw", "today", "tolabel", "tomorrow", "transaction", + "trigger", "true", "try", "type", "undelete", "update", "upsert", "using", + "virtual", "webservice", "when", "where", "while", "yesterday" + )); languageSpecificPrimitives = new HashSet( - Arrays.asList("Blob", "Boolean", "Date", "Datetime", "Decimal", "Double", "ID", - "Integer", "Long", "Object", "String", "Time" - )); + Arrays.asList("Blob", "Boolean", "Date", "Datetime", "Decimal", "Double", "ID", + "Integer", "Long", "Object", "String", "Time" + )); } @Override @@ -114,12 +129,12 @@ public void processOpts() { additionalProperties.put(API_VERSION, apiVersion); if (additionalProperties.containsKey(BUILD_METHOD)) { - setBuildMethod((String)additionalProperties.get(BUILD_METHOD)); + setBuildMethod((String) additionalProperties.get(BUILD_METHOD)); } additionalProperties.put(BUILD_METHOD, buildMethod); if (additionalProperties.containsKey(NAMED_CREDENTIAL)) { - setNamedCredential((String)additionalProperties.get(NAMED_CREDENTIAL)); + setNamedCredential((String) additionalProperties.get(NAMED_CREDENTIAL)); } additionalProperties.put(NAMED_CREDENTIAL, namedCredential); @@ -144,29 +159,27 @@ public String toModelName(String name) { } @Override - public String toDefaultValue(Property p) { + public String toDefaultValue(Schema p) { String out = null; - if (p instanceof ArrayProperty) { - Property inner = ((ArrayProperty) p).getItems(); + if (ModelUtils.isArraySchema(p)) { + Schema inner = ((ArraySchema) p).getItems(); out = String.format( - "new List<%s>()", - inner == null ? "Object" : getTypeDeclaration(inner) + "new List<%s>()", + inner == null ? "Object" : getTypeDeclaration(inner) ); - } else if (p instanceof BooleanProperty) { + } else if (ModelUtils.isBooleanSchema(p)) { // true => "true", false => "false", null => "null" - out = String.valueOf(((BooleanProperty) p).getDefault()); - } else if (p instanceof LongProperty) { - Long def = ((LongProperty) p).getDefault(); - out = def == null ? out : def.toString() + "L"; - } else if (p instanceof MapProperty) { - Property inner = ((MapProperty) p).getAdditionalProperties(); + out = String.valueOf(((BooleanSchema) p).getDefault()); + } else if (ModelUtils.isLongSchema(p)) { // long + out = p.getDefault() == null ? out : p.getDefault().toString() + "L"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); String s = inner == null ? "Object" : getTypeDeclaration(inner); out = String.format("new Map()", s); - } else if (p instanceof StringProperty) { - StringProperty sp = (StringProperty) p; - String def = sp.getDefault(); + } else if (ModelUtils.isStringSchema(p)) { + String def = (String) p.getDefault(); if (def != null) { - out = sp.getEnum() == null ? String.format("'%s'", escapeText(def)) : def; + out = p.getEnum() == null ? String.format("'%s'", escapeText(def)) : def; } } else { out = super.toDefaultValue(p); @@ -199,7 +212,7 @@ public void setParameterExampleValue(CodegenParameter p) { } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel cm = super.fromModel(name, model, allDefinitions); if (cm.interfaces == null) { cm.interfaces = new ArrayList(); @@ -239,14 +252,14 @@ public void postProcessParameter(CodegenParameter parameter) { } @Override - public void preprocessSwagger(Swagger swagger) { - Info info = swagger.getInfo(); + public void preprocessOpenAPI(OpenAPI openAPI) { + Info info = openAPI.getInfo(); String calloutLabel = info.getTitle(); additionalProperties.put("calloutLabel", calloutLabel); String sanitized = sanitizeName(calloutLabel); additionalProperties.put("calloutName", sanitized); supportingFiles.add(new SupportingFile("namedCredential.mustache", srcPath + "/namedCredentials", - sanitized + ".namedCredential" + sanitized + ".namedCredential" )); if (additionalProperties.get(BUILD_METHOD).equals("sfdx")) { @@ -261,31 +274,28 @@ public void preprocessSwagger(Swagger swagger) { public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, - Map definitions, - Swagger swagger) { + Map definitions, + OpenAPI openAPI) { Boolean hasFormParams = false; - for (Parameter p : operation.getParameters()) { - if ("formData".equals(p.getIn())) { - hasFormParams = true; - break; - } - } - + // comment out the following as there's no consume/produce in OAS3.0 + // we can move the logic below to postProcessOperations if needed + /* // only support serialization into JSON and urlencoded forms for now operation.setConsumes( - Collections.singletonList(hasFormParams + Collections.singletonList(hasFormParameter(operation) ? "application/x-www-form-urlencoded" : "application/json")); // only support deserialization from JSON for now operation.setProduces(Collections.singletonList("application/json")); + */ + + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, openAPI); - CodegenOperation op = super.fromOperation( - path, httpMethod, operation, definitions, swagger); if (op.getHasExamples()) { // prepare examples for Apex test classes - Property responseProperty = findMethodResponse(operation.getResponses()).getSchema(); - String deserializedExample = toExampleValue(responseProperty); + ApiResponse responseProperty = findMethodResponse(operation.getResponses()); + String deserializedExample = toExampleValue(getSchemaFromResponse(responseProperty)); for (Map example : op.examples) { example.put("example", escapeText(example.get("example"))); example.put("deserializedExample", deserializedExample); @@ -335,9 +345,9 @@ private String toApiVersion(String apiVersion) { private void postProcessOpts() { supportingFiles.add( - new SupportingFile("client.mustache", srcPath + "classes", classPrefix + "Client.cls")); + new SupportingFile("client.mustache", srcPath + "classes", classPrefix + "Client.cls")); supportingFiles.add(new SupportingFile("cls-meta.mustache", srcPath + "classes", - classPrefix + "Client.cls-meta.xml" + classPrefix + "Client.cls-meta.xml" )); } @@ -356,92 +366,89 @@ public String toModelTestFilename(String name) { } @Override - public String toExampleValue(Property p) { + public String toExampleValue(Schema p) { if (p == null) { return ""; } Object obj = p.getExample(); String example = obj == null ? "" : obj.toString(); - if (p instanceof ArrayProperty) { + if (ModelUtils.isArraySchema(p)) { // array example = "new " + getTypeDeclaration(p) + "{" + toExampleValue( - ((ArrayProperty) p).getItems()) + "}"; - } else if (p instanceof BooleanProperty) { + ((ArraySchema) p).getItems()) + "}"; + } else if (ModelUtils.isBooleanSchema(p)) { example = String.valueOf(!"false".equals(example)); - } else if (p instanceof ByteArrayProperty) { + } else if (ModelUtils.isByteArraySchema(p)) { // byte array if (example.isEmpty()) { example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"; } - ((ByteArrayProperty) p).setExample(example); + ((ByteArraySchema) p).setExample(example); example = "EncodingUtil.base64Decode('" + example + "')"; - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { // date if (example.matches("^\\d{4}(-\\d{2}){2}")) { example = example.substring(0, 10).replaceAll("-0?", ", "); } else if (example.isEmpty()) { example = "2000, 1, 23"; } else { LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 date. Defaulting to '2000-01-23'. [%s]", p - .getName(), example)); + .getName(), example)); example = "2000, 1, 23"; } example = "Date.newInstance(" + example + ")"; - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { // datetime if (example.matches("^\\d{4}([-T:]\\d{2}){5}.+")) { example = example.substring(0, 19).replaceAll("[-T:]0?", ", "); } else if (example.isEmpty()) { example = "2000, 1, 23, 4, 56, 7"; } else { LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 datetime. Defaulting to '2000-01-23T04-56-07Z'. [%s]", p - .getName(), example)); + .getName(), example)); example = "2000, 1, 23, 4, 56, 7"; } example = "Datetime.newInstanceGmt(" + example + ")"; - } else if (p instanceof DecimalProperty) { + } else if (ModelUtils.isNumberSchema(p)) { // number example = example.replaceAll("[^-0-9.]", ""); example = example.isEmpty() ? "1.3579" : example; - } else if (p instanceof FileProperty) { + } else if (ModelUtils.isFileSchema(p)) { // file if (example.isEmpty()) { example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"; - ((FileProperty) p).setExample(example); + ((FileSchema) p).setExample(example); } example = "EncodingUtil.base64Decode(" + example + ")"; - } else if (p instanceof EmailProperty) { + } else if (ModelUtils.isEmailSchema(p)) { // email if (example.isEmpty()) { example = "example@example.com"; - ((EmailProperty) p).setExample(example); + ((EmailSchema) p).setExample(example); } example = "'" + example + "'"; - } else if (p instanceof LongProperty) { + } else if (ModelUtils.isLongSchema(p)) { // long example = example.isEmpty() ? "123456789L" : example + "L"; - } else if (p instanceof MapProperty) { + } else if (ModelUtils.isMapSchema(p)) { // map example = "new " + getTypeDeclaration(p) + "{'key'=>" + toExampleValue( - ((MapProperty) p).getAdditionalProperties()) + "}"; - } else if (p instanceof ObjectProperty) { + (Schema) p.getAdditionalProperties()) + "}"; + } else if (ModelUtils.isObjectSchema(p)) { // object example = example.isEmpty() ? "null" : example; - } else if (p instanceof PasswordProperty) { + } else if (ModelUtils.isPasswordSchema(p)) { // password example = example.isEmpty() ? "password123" : escapeText(example); - ((PasswordProperty) p).setExample(example); + ((PasswordSchema) p).setExample(example); example = "'" + example + "'"; - } else if (p instanceof RefProperty) { + } else if (!StringUtils.isEmpty(p.get$ref())) { example = getTypeDeclaration(p) + ".getExample()"; - } else if (p instanceof StringProperty) { - StringProperty sp = (StringProperty) p; - List enums = sp.getEnum(); + } else if (ModelUtils.isUUIDSchema(p)) { + example = example.isEmpty() + ? "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'" + : "'" + escapeText(example) + "'"; + } else if (ModelUtils.isStringSchema(p)) { // string + List enums = p.getEnum(); if (enums != null && example.isEmpty()) { example = enums.get(0); - sp.setExample(example); + p.setExample(example); } else if (example.isEmpty()) { example = "aeiou"; } else { example = escapeText(example); - sp.setExample(example); + p.setExample(example); } example = "'" + example + "'"; - } else if (p instanceof UUIDProperty) { - example = example.isEmpty() - ? "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'" - : "'" + escapeText(example) + "'"; - } else if (p instanceof BaseIntegerProperty) { - example = example.matches("^-?\\d+$") ? example : "123"; } return example; @@ -488,16 +495,11 @@ private void generateAntSupportingFiles() { supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); writeOptional(outputFolder, new SupportingFile("README_ant.mustache", "README.md")); - } private void generateSfdxSupportingFiles() { - supportingFiles.add(new SupportingFile("sfdx.mustache", "", "sfdx-oss-manifest.json")); - writeOptional(outputFolder, new SupportingFile("README_sfdx.mustache", "README.md")); - } - } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java index edbd41a56cec..59504fd3fe5f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java @@ -6,8 +6,7 @@ import com.samskivert.mustache.Mustache; import org.openapitools.codegen.*; -import io.swagger.models.*; -import io.swagger.util.Json; +import org.openapitools.codegen.utils.ModelUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,7 +36,7 @@ public AspNetCoreServerCodegen() { // contextually reserved words // NOTE: C# uses camel cased reserved words, while models are title cased. We don't want lowercase comparisons. reservedWords.addAll( - Arrays.asList("var", "async", "await", "dynamic", "yield") + Arrays.asList("var", "async", "await", "dynamic", "yield") ); cliOptions.clear(); @@ -100,7 +99,7 @@ public void processOpts() { setPackageGuid((String) additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_GUID)); } additionalProperties.put("packageGuid", packageGuid); - + additionalProperties.put("dockerTag", this.packageName.toLowerCase()); apiPackage = packageName + ".Controllers"; @@ -133,17 +132,17 @@ public void processOpts() { supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "index.html", packageFolder + File.separator + "wwwroot", "index.html")); supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "web.config", packageFolder + File.separator + "wwwroot", "web.config")); - supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "swagger-original.mustache", packageFolder + File.separator + "wwwroot", "swagger-original.json")); + supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "openapi-original.mustache", packageFolder + File.separator + "wwwroot", "openapi-original.json")); } @Override public void setSourceFolder(final String sourceFolder) { - if(sourceFolder == null) { + if (sourceFolder == null) { LOGGER.warn("No sourceFolder specified, using default"); - this.sourceFolder = "src" + File.separator + this.packageName; - } else if(!sourceFolder.equals("src") && !sourceFolder.startsWith("src")) { + this.sourceFolder = "src" + File.separator + this.packageName; + } else if (!sourceFolder.equals("src") && !sourceFolder.startsWith("src")) { LOGGER.warn("ASP.NET Core requires source code exists under src. Adjusting."); - this.sourceFolder = "src" + File.separator + sourceFolder; + this.sourceFolder = "src" + File.separator + sourceFolder; } else { this.sourceFolder = sourceFolder; } @@ -152,7 +151,7 @@ public void setSourceFolder(final String sourceFolder) { public void setPackageGuid(String packageGuid) { this.packageGuid = packageGuid; } - + @Override public String apiFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Controllers"; @@ -160,20 +159,13 @@ public String apiFileFolder() { @Override public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Models"; + return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Models"; } @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { - try { - objs.put("swagger-json", Json.pretty().writeValueAsString(swagger).replace("\r\n", "\n")); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } + generateJSONSpecFile(objs); return super.postProcessSupportingFileData(objs); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java index d930775a4d24..76bcfd395c7a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java @@ -3,6 +3,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; + +import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenOperation; @@ -10,15 +12,13 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.models.parameters.BodyParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.parameters.SerializableParameter; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.parameters.*; + import org.apache.commons.lang3.StringEscapeUtils; import java.util.Arrays; @@ -29,661 +29,633 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String apiVersion = "1.0.0"; - - protected String curlOptions; - protected boolean processMarkdown = false; - protected String scriptName = "client.sh"; - protected boolean generateBashCompletion = false; - protected boolean generateZshCompletion = false; - protected String hostEnvironmentVariable; - protected String basicAuthEnvironmentVariable; - protected String apiKeyAuthEnvironmentVariable; - protected String apiDocPath = "docs/"; - protected String modelDocPath = "docs/"; - - public static final String CURL_OPTIONS = "curlOptions"; - public static final String PROCESS_MARKDOWN = "processMarkdown"; - public static final String SCRIPT_NAME = "scriptName"; - public static final String - GENERATE_BASH_COMPLETION = "generateBashCompletion"; - public static final String - GENERATE_ZSH_COMPLETION = "generateZshCompletion"; - public static final String - HOST_ENVIRONMENT_VARIABLE_NAME = "hostEnvironmentVariable"; - public static final String - BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME = "basicAuthEnvironmentVariable"; - public static final String - APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME = "apiKeyAuthEnvironmentVariable"; - - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see org.openapitools.codegen.CodegenType - */ - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - /** - * Configures a friendly name for the generator. This will be used by - * the generator to select the library with the -l flag. - * - * @return the friendly name for the generator - */ - public String getName() { - return "bash"; - } - - /** - * Returns human-friendly help for the generator. Provide the consumer with - * help tips, parameters here - * - * @return A string value for the help message - */ - public String getHelp() { - return "Generates a Bash client script based on cURL."; - } - - public BashClientCodegen() { - super(); + protected String apiVersion = "1.0.0"; + + protected String curlOptions; + protected boolean processMarkdown = false; + protected String scriptName = "client.sh"; + protected boolean generateBashCompletion = false; + protected boolean generateZshCompletion = false; + protected String hostEnvironmentVariable; + protected String basicAuthEnvironmentVariable; + protected String apiKeyAuthEnvironmentVariable; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + + public static final String CURL_OPTIONS = "curlOptions"; + public static final String PROCESS_MARKDOWN = "processMarkdown"; + public static final String SCRIPT_NAME = "scriptName"; + public static final String + GENERATE_BASH_COMPLETION = "generateBashCompletion"; + public static final String + GENERATE_ZSH_COMPLETION = "generateZshCompletion"; + public static final String + HOST_ENVIRONMENT_VARIABLE_NAME = "hostEnvironmentVariable"; + public static final String + BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME = "basicAuthEnvironmentVariable"; + public static final String + APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME = "apiKeyAuthEnvironmentVariable"; /** - * Set the output folder here + * Configures the type of generator. + * + * @return the CodegenType for this generator */ - outputFolder = "generated-code/bash"; + public CodegenType getTag() { + return CodegenType.CLIENT; + } /** - * No model files. + * Configures a friendly name for the generator. This will be used by + * the generator to select the library with the -l flag. + * + * @return the friendly name for the generator */ - modelTemplateFiles.clear(); - + public String getName() { + return "bash"; + } /** - * No API files. + * Returns human-friendly help for the generator. Provide the consumer with + * help tips, parameters here + * + * @return A string value for the help message */ - apiTemplateFiles.clear(); + public String getHelp() { + return "Generates a Bash client script based on cURL."; + } + public BashClientCodegen() { + super(); - /** - * docs files. - */ - modelDocTemplateFiles.put("model_doc.mustache", ".md"); - apiDocTemplateFiles.put("api_doc.mustache", ".md"); + /** + * Set the output folder here + */ + outputFolder = "generated-code/bash"; + /** + * No model files. + */ + modelTemplateFiles.clear(); - /** - * Templates location for client script and bash completion template. - */ - embeddedTemplateDir = templateDir = "bash"; + /** + * No API files. + */ + apiTemplateFiles.clear(); - /** - * Allow the user to force the script to always include certain cURL - * comamnds - */ - cliOptions.add(CliOption.newString(CURL_OPTIONS, "Default cURL options")); - cliOptions.add(CliOption.newBoolean(PROCESS_MARKDOWN, - "Convert all Markdown Markup into terminal formatting")); - cliOptions.add(CliOption.newString(SCRIPT_NAME, - "The name of the script that will be generated "+ - "(e.g. petstore-cli)")); - cliOptions.add(CliOption.newBoolean(GENERATE_BASH_COMPLETION, - "Whether to generate the Bash completion script")); - cliOptions.add(CliOption.newBoolean(GENERATE_ZSH_COMPLETION, - "Whether to generate the Zsh completion script")); - cliOptions.add(CliOption.newString(HOST_ENVIRONMENT_VARIABLE_NAME, - "Name of environment variable where host can be defined "+ - "(e.g. PETSTORE_HOST='http://petstore.swagger.io:8080')")); - cliOptions.add(CliOption.newString(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME, - "Name of environment variable where username and password " - + - "can be defined (e.g. PETSTORE_CREDS='username:password')")); - cliOptions.add(CliOption.newBoolean(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, - "Name of environment variable where API key " - + - "can be defined (e.g. PETSTORE_APIKEY='kjhasdGASDa5asdASD')")); - /** - * Bash reserved words. - */ - reservedWords = new HashSet ( - Arrays.asList( - "case", - "do", - "done", - "elif", - "else", - "esac", - "fi", - "for", - "function", - "if", - "in", - "select", - "then", - "time", - "until", - "while") - ); - - typeMapping.clear(); - typeMapping.put("array", "array"); - typeMapping.put("map", "map"); - typeMapping.put("List", "array"); - typeMapping.put("boolean", "boolean"); - typeMapping.put("string", "string"); - typeMapping.put("int", "integer"); - typeMapping.put("float", "float"); - typeMapping.put("number", "integer"); - typeMapping.put("date", "string"); - typeMapping.put("DateTime", "string"); - typeMapping.put("long", "integer"); - typeMapping.put("short", "integer"); - typeMapping.put("char", "string"); - typeMapping.put("double", "float"); - typeMapping.put("object", "map"); - typeMapping.put("integer", "integer"); - typeMapping.put("ByteArray", "string"); - typeMapping.put("binary", "binary"); - typeMapping.put("UUID", "string"); + /** + * docs files. + */ + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); - /** - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files. - */ - additionalProperties.put("apiVersion", apiVersion); - // make api and model doc path available in mustache template - additionalProperties.put("apiDocPath", apiDocPath); - additionalProperties.put("modelDocPath", modelDocPath); - /** - * Language Specific Primitives. These types will not trigger imports by - * the client generator - */ - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("array"); - languageSpecificPrimitives.add("map"); - languageSpecificPrimitives.add("boolean"); - languageSpecificPrimitives.add("integer"); - languageSpecificPrimitives.add("float"); - languageSpecificPrimitives.add("string"); - languageSpecificPrimitives.add("binary"); - } - - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(CURL_OPTIONS)) { - setCurlOptions(additionalProperties.get(CURL_OPTIONS).toString()); - additionalProperties.put("x-codegen-curl-options", this.curlOptions); - } + /** + * Templates location for client script and bash completion template. + */ + embeddedTemplateDir = templateDir = "bash"; - if (additionalProperties.containsKey(PROCESS_MARKDOWN)) { - setProcessMarkdown(convertPropertyToBooleanAndWriteBack(PROCESS_MARKDOWN)); - } - if (additionalProperties.containsKey(GENERATE_BASH_COMPLETION)) { - setGenerateBashCompletion(convertPropertyToBooleanAndWriteBack(GENERATE_BASH_COMPLETION)); - } + /** + * Allow the user to force the script to always include certain cURL + * comamnds + */ + cliOptions.add(CliOption.newString(CURL_OPTIONS, "Default cURL options")); + cliOptions.add(CliOption.newBoolean(PROCESS_MARKDOWN, + "Convert all Markdown Markup into terminal formatting")); + cliOptions.add(CliOption.newString(SCRIPT_NAME, + "The name of the script that will be generated " + + "(e.g. petstore-cli)")); + cliOptions.add(CliOption.newBoolean(GENERATE_BASH_COMPLETION, + "Whether to generate the Bash completion script")); + cliOptions.add(CliOption.newBoolean(GENERATE_ZSH_COMPLETION, + "Whether to generate the Zsh completion script")); + cliOptions.add(CliOption.newString(HOST_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where host can be defined " + + "(e.g. PETSTORE_HOST='http://petstore.swagger.io:8080')")); + cliOptions.add(CliOption.newString(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where username and password " + + + "can be defined (e.g. PETSTORE_CREDS='username:password')")); + cliOptions.add(CliOption.newBoolean(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where API key " + + + "can be defined (e.g. PETSTORE_APIKEY='kjhasdGASDa5asdASD')")); - if (additionalProperties.containsKey(GENERATE_ZSH_COMPLETION)) { - setGenerateZshCompletion(convertPropertyToBooleanAndWriteBack(GENERATE_ZSH_COMPLETION)); - } + /** + * Bash reserved words. + */ + reservedWords = new HashSet( + Arrays.asList( + "case", + "do", + "done", + "elif", + "else", + "esac", + "fi", + "for", + "function", + "if", + "in", + "select", + "then", + "time", + "until", + "while") + ); + + typeMapping.clear(); + typeMapping.put("array", "array"); + typeMapping.put("map", "map"); + typeMapping.put("List", "array"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("int", "integer"); + typeMapping.put("float", "float"); + typeMapping.put("number", "integer"); + typeMapping.put("date", "string"); + typeMapping.put("DateTime", "string"); + typeMapping.put("long", "integer"); + typeMapping.put("short", "integer"); + typeMapping.put("char", "string"); + typeMapping.put("double", "float"); + typeMapping.put("object", "map"); + typeMapping.put("integer", "integer"); + typeMapping.put("ByteArray", "string"); + typeMapping.put("binary", "binary"); + typeMapping.put("UUID", "string"); - if (additionalProperties.containsKey(SCRIPT_NAME)) { - setScriptName(additionalProperties.get(SCRIPT_NAME).toString()); - } - additionalProperties.put("x-codegen-script-name", scriptName); + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files. + */ + additionalProperties.put("apiVersion", apiVersion); + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); - if (additionalProperties.containsKey(HOST_ENVIRONMENT_VARIABLE_NAME)) { - setHostEnvironmentVariable( - additionalProperties.get(HOST_ENVIRONMENT_VARIABLE_NAME).toString()); - additionalProperties.put("x-codegen-host-env", hostEnvironmentVariable); - } + /** + * Language Specific Primitives. These types will not trigger imports by + * the client generator + */ + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("array"); + languageSpecificPrimitives.add("map"); + languageSpecificPrimitives.add("boolean"); + languageSpecificPrimitives.add("integer"); + languageSpecificPrimitives.add("float"); + languageSpecificPrimitives.add("string"); + languageSpecificPrimitives.add("binary"); + } - if (additionalProperties.containsKey(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME)) { - setBasicAuthEnvironmentVariable( - additionalProperties.get(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); - additionalProperties.put("x-codegen-basicauth-env", basicAuthEnvironmentVariable); - } - if (additionalProperties.containsKey(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME)) { - setApiKeyAuthEnvironmentVariable( - additionalProperties.get(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); - additionalProperties.put("x-codegen-apikey-env", apiKeyAuthEnvironmentVariable); - } + @Override + public void processOpts() { + super.processOpts(); - supportingFiles.add(new SupportingFile( - "client.mustache", "", scriptName)); - supportingFiles.add(new SupportingFile( - "bash-completion.mustache", "", scriptName+".bash-completion")); - supportingFiles.add(new SupportingFile( - "zsh-completion.mustache", "", "_"+scriptName)); - supportingFiles.add(new SupportingFile( - "README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile( - "Dockerfile.mustache", "", "Dockerfile")); - } - - public void setCurlOptions(String curlOptions) { - this.curlOptions = curlOptions; - } - - public void setProcessMarkdown(boolean processMarkdown) { - this.processMarkdown = processMarkdown; - } - - public void setScriptName(String scriptName) { - this.scriptName = scriptName; - } - - public void setGenerateBashCompletion(boolean generateBashCompletion) { - this.generateBashCompletion = generateBashCompletion; - } - - public void setGenerateZshCompletion(boolean generateZshCompletion) { - this.generateZshCompletion = generateZshCompletion; - } - - public void setHostEnvironmentVariable(String hostEnvironmentVariable) { - this.hostEnvironmentVariable = hostEnvironmentVariable; - } - - public void setBasicAuthEnvironmentVariable(String - basicAuthEnvironmentVariable) { - this.basicAuthEnvironmentVariable = basicAuthEnvironmentVariable; - } - - public void setApiKeyAuthEnvironmentVariable(String - apiKeyAuthEnvironmentVariable) { - this.apiKeyAuthEnvironmentVariable = apiKeyAuthEnvironmentVariable; - } - - - /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle - * escaping those terms here. This logic is only called if a variable - * matches the reserved words. - * - * @return the escaped term - */ - @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name - } - - /** - * Location to write model files. You can use the modelPackage() as defined - * when the class is instantiated. - */ - public String modelFileFolder() { - return outputFolder; - } - - /** - * Location to write api files. You can use the apiPackage() as defined when - * the class is instantiated. - */ - @Override - public String apiFileFolder() { - return outputFolder; - } - - @Override - public String apiDocFileFolder() { - return (outputFolder + "/" + apiDocPath); - } - - @Override - public String modelDocFileFolder() { - return (outputFolder + "/" + modelDocPath); - } - - @Override - public String toModelDocFilename(String name) { - return toModelName(name); - } - - @Override - public String toApiDocFilename(String name) { - return toApiName(name); - } - - /** - * Optional - type declaration. This is a String which is used by the - * templates to instantiate your types. There is typically special handling - * for different property types - * - * @return a string value used as the `dataType` field for model templates, - * `returnType` for api templates - */ - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + if (additionalProperties.containsKey(CURL_OPTIONS)) { + setCurlOptions(additionalProperties.get(CURL_OPTIONS).toString()); + additionalProperties.put("x-codegen-curl-options", this.curlOptions); + } + + if (additionalProperties.containsKey(PROCESS_MARKDOWN)) { + setProcessMarkdown(convertPropertyToBooleanAndWriteBack(PROCESS_MARKDOWN)); + } + + if (additionalProperties.containsKey(GENERATE_BASH_COMPLETION)) { + setGenerateBashCompletion(convertPropertyToBooleanAndWriteBack(GENERATE_BASH_COMPLETION)); + } + + if (additionalProperties.containsKey(GENERATE_ZSH_COMPLETION)) { + setGenerateZshCompletion(convertPropertyToBooleanAndWriteBack(GENERATE_ZSH_COMPLETION)); + } + + if (additionalProperties.containsKey(SCRIPT_NAME)) { + setScriptName(additionalProperties.get(SCRIPT_NAME).toString()); + } + additionalProperties.put("x-codegen-script-name", scriptName); + + if (additionalProperties.containsKey(HOST_ENVIRONMENT_VARIABLE_NAME)) { + setHostEnvironmentVariable( + additionalProperties.get(HOST_ENVIRONMENT_VARIABLE_NAME).toString()); + additionalProperties.put("x-codegen-host-env", hostEnvironmentVariable); + } + + if (additionalProperties.containsKey(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME)) { + setBasicAuthEnvironmentVariable( + additionalProperties.get(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); + additionalProperties.put("x-codegen-basicauth-env", basicAuthEnvironmentVariable); + } + + if (additionalProperties.containsKey(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME)) { + setApiKeyAuthEnvironmentVariable( + additionalProperties.get(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); + additionalProperties.put("x-codegen-apikey-env", apiKeyAuthEnvironmentVariable); + } + + supportingFiles.add(new SupportingFile( + "client.mustache", "", scriptName)); + supportingFiles.add(new SupportingFile( + "bash-completion.mustache", "", scriptName + ".bash-completion")); + supportingFiles.add(new SupportingFile( + "zsh-completion.mustache", "", "_" + scriptName)); + supportingFiles.add(new SupportingFile( + "README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile( + "Dockerfile.mustache", "", "Dockerfile")); + } + + public void setCurlOptions(String curlOptions) { + this.curlOptions = curlOptions; + } + + public void setProcessMarkdown(boolean processMarkdown) { + this.processMarkdown = processMarkdown; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public void setGenerateBashCompletion(boolean generateBashCompletion) { + this.generateBashCompletion = generateBashCompletion; } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + + public void setGenerateZshCompletion(boolean generateZshCompletion) { + this.generateZshCompletion = generateZshCompletion; } - return super.getTypeDeclaration(p); - } - - /** - * Optional - swagger type conversion. This is used to map swagger types in - * a `Property` into either language specific types via `typeMapping` or into - * complex models if there is not a mapping. - * - * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property - */ - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) - return type; + + public void setHostEnvironmentVariable(String hostEnvironmentVariable) { + this.hostEnvironmentVariable = hostEnvironmentVariable; } - else { - type = swaggerType; + + public void setBasicAuthEnvironmentVariable(String + basicAuthEnvironmentVariable) { + this.basicAuthEnvironmentVariable = basicAuthEnvironmentVariable; } - return toModelName(type); - } + public void setApiKeyAuthEnvironmentVariable(String + apiKeyAuthEnvironmentVariable) { + this.apiKeyAuthEnvironmentVariable = apiKeyAuthEnvironmentVariable; + } - /** - * Convert Swagger Parameter object to Codegen Parameter object - * - * @param param Swagger parameter object - * @param imports set of imports for library/package/module - * @return Codegen Parameter object - */ - @Override - public CodegenParameter fromParameter(Parameter param, Set imports) { - CodegenParameter p = super.fromParameter(param, imports); + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle + * escaping those terms here. This logic is only called if a variable + * matches the reserved words. + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } - if(param instanceof BodyParameter) { + /** + * Location to write model files. You can use the modelPackage() as defined + * when the class is instantiated. + */ + public String modelFileFolder() { + return outputFolder; + } - Model model = ((BodyParameter)param).getSchema(); + /** + * Location to write api files. You can use the apiPackage() as defined when + * the class is instantiated. + */ + @Override + public String apiFileFolder() { + return outputFolder; + } + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath); } - else if(param instanceof SerializableParameter) { - /** - * Currently it's not possible to specify in the codegen other collection - * formats than 'multi' - */ - SerializableParameter sparam = (SerializableParameter)param; + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath); + } - if( sparam.getCollectionFormat() != null - && !sparam.getCollectionFormat().isEmpty()) { + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } - String collectionFormat = sparam.getCollectionFormat(); + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } - if(sparam.isExclusiveMaximum()!=null && sparam.isExclusiveMaximum()) { - p.vendorExtensions.put("x-codegen-collection-max-items", - sparam.getMaxItems()); + /** + * Optional - type declaration. This is a String which is used by the + * templates to instantiate your types. There is typically special handling + * for different property types + * + * @return a string value used as the `dataType` field for model templates, + * `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; } + return super.getTypeDeclaration(p); + } - if(sparam.isExclusiveMinimum()!=null && sparam.isExclusiveMinimum()) { - p.vendorExtensions.put("x-codegen-collection-min-items", - sparam.getMinItems()); + /** + * Optional - schema type conversion. This is used to map OpenAPI types in + * a `Property` into either language specific types via `typeMapping` or into + * complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + * @see io.swagger.v3.oas.models.media.Schema + */ + @Override + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); + String type = null; + if (typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); + if (languageSpecificPrimitives.contains(type)) + return type; + } else { + type = schemaType; } + return toModelName(type); + } - if( (collectionFormat.equals("multi")) - && (param.getIn().equals("query")) ) { - /** - * 'multi' is only supported for query parameters - */ - p.vendorExtensions.put("x-codegen-collection-multi", true); + /** + * Convert OpenAPI Parameter object to Codegen Parameter object + * + * @param param OpenAPI parameter object + * @param imports set of imports for library/package/module + * @return Codegen Parameter object + */ + @Override + public CodegenParameter fromParameter(Parameter param, Set imports) { - } - else if(collectionFormat.equals("csv")) { - p.vendorExtensions.put("x-codegen-collection-csv", true); - } - else if(collectionFormat.equals("ssv")) { - p.vendorExtensions.put("x-codegen-collection-ssv", true); - } - else if(collectionFormat.equals("tsv")) { - p.vendorExtensions.put("x-codegen-collection-tsv", true); - } - else if(collectionFormat.equals("pipes")) { - p.vendorExtensions.put("x-codegen-collection-pipes", true); - } - else { - /** Unsupported collection format */ - } + CodegenParameter p = super.fromParameter(param, imports); - } + if (p.isContainer) { // array or map + /** + * Currently it's not possible to specify in the codegen other collection + * formats than 'multi' + */ + if (!StringUtils.isEmpty(p.collectionFormat)) { + if (Boolean.TRUE.equals(p.exclusiveMaximum)) { + p.vendorExtensions.put("x-codegen-collection-max-items", + p.maxItems); + } - } + if (Boolean.TRUE.equals(p.exclusiveMinimum)) { + p.vendorExtensions.put("x-codegen-collection-min-items", + p.minItems); + } - return p; + if ("multi".equals(p.collectionFormat) && Boolean.TRUE.equals(p.isQueryParam)) { + //'multi' is only supported for query parameters + p.vendorExtensions.put("x-codegen-collection-multi", true); + } else if ("csv".equals(p.collectionFormat)) { + p.vendorExtensions.put("x-codegen-collection-csv", true); + } else if ("ssv".equals(p.collectionFormat)) { + p.vendorExtensions.put("x-codegen-collection-ssv", true); + } else if ("tsv".equals(p.collectionFormat)) { + p.vendorExtensions.put("x-codegen-collection-tsv", true); + } else if ("pipes".equals(p.collectionFormat)) { + p.vendorExtensions.put("x-codegen-collection-pipes", true); + } else { + LOGGER.warn("Unsupported collection format in Bash generator: " + p.collectionFormat); + } + } + } - } + return p; - /** - * Override with any special text escaping logic - */ - @SuppressWarnings("static-method") - public String escapeText(String input) { - if (input == null) { - return input; - } + } - /** - * Trim the input text always. - */ - String result = input.trim(); - - /** - * remove standalone '\' - * - * replace " with \" - * outter unescape to retain the original multi-byte characters - */ - result = escapeUnsafeCharacters( - StringEscapeUtils.unescapeJava( - StringEscapeUtils.escapeJava(result).replace("\\/", "/")) - .replace("\\", "\\\\") - .replace("\"", "\\\"")); - - if(this.processMarkdown) { + /** + * Override with any special text escaping logic + */ + @SuppressWarnings("static-method") + public String escapeText(String input) { + if (input == null) { + return input; + } /** - * Convert markdown strong **Bold text** and __Bold text__ - * to bash bold control sequences (tput bold) + * Trim the input text always. */ - result = result.replaceAll("(?m)(^|\\s)\\*{2}([\\w\\d ]+)\\*{2}($|\\s)", - "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); + String result = input.trim(); - result = result.replaceAll("(?m)(^|\\s)_{2}([\\w\\d ]+)_{2}($|\\s)", - "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); /** - * Convert markdown *Italics text* and _Italics text_ to bash dim - * control sequences (tput dim) + * remove standalone '\' + * + * replace " with \" + * outter unescape to retain the original multi-byte characters */ - result = result.replaceAll("(?m)(^|\\s)\\*{1}([\\w\\d ]+)\\*{1}($|\\s)", - "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); + result = escapeUnsafeCharacters( + StringEscapeUtils.unescapeJava( + StringEscapeUtils.escapeJava(result).replace("\\/", "/")) + .replace("\\", "\\\\") + .replace("\"", "\\\"")); - result = result.replaceAll("(?m)(^|\\s)_{1}([\\w\\d ]+)_{1}($|\\s)", - "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); + if (this.processMarkdown) { + /** + * Convert markdown strong **Bold text** and __Bold text__ + * to bash bold control sequences (tput bold) + */ + result = result.replaceAll("(?m)(^|\\s)\\*{2}([\\w\\d ]+)\\*{2}($|\\s)", + "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); - /** - * Convert all markdown section 1 level headers with bold - */ - result = result.replaceAll("(?m)^\\#\\s+(.+)$", - "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" - +"$1\\$\\(tput sgr0\\)"); + result = result.replaceAll("(?m)(^|\\s)_{2}([\\w\\d ]+)_{2}($|\\s)", + "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); + /** + * Convert markdown *Italics text* and _Italics text_ to bash dim + * control sequences (tput dim) + */ + result = result.replaceAll("(?m)(^|\\s)\\*{1}([\\w\\d ]+)\\*{1}($|\\s)", + "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); - /** - * Convert all markdown section 2 level headers with bold - */ - result = result.replaceAll("(?m)^\\#\\#\\s+(.+)$", - "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" - +"$1\\$\\(tput sgr0\\)"); + result = result.replaceAll("(?m)(^|\\s)_{1}([\\w\\d ]+)_{1}($|\\s)", + "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); - /** - * Convert all markdown section 3 level headers with bold - */ - result = result.replaceAll("(?m)^\\#\\#\\#\\s+(.+)$", - "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" - +"$1\\$\\(tput sgr0\\)"); - /** - * Convert all markdown code blocks into --- delimited sections - */ - result = result.replaceAll("(?m)\\s*```.*$", - "\n---"); + /** + * Convert all markdown section 1 level headers with bold + */ + result = result.replaceAll("(?m)^\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + + "$1\\$\\(tput sgr0\\)"); - result = result.replaceAll("(?m)\\s*\\'\\'\\'.*$", - "\n---"); + /** + * Convert all markdown section 2 level headers with bold + */ + result = result.replaceAll("(?m)^\\#\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + + "$1\\$\\(tput sgr0\\)"); - /** - * Remove any trailing new line at the end of the string - */ - result = result.replaceAll("\\s+$", ""); - } + /** + * Convert all markdown section 3 level headers with bold + */ + result = result.replaceAll("(?m)^\\#\\#\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + + "$1\\$\\(tput sgr0\\)"); - return result; - } + /** + * Convert all markdown code blocks into --- delimited sections + */ + result = result.replaceAll("(?m)\\s*```.*$", + "\n---"); - @Override - public String escapeQuotationMark(String input) { - return input; - } + result = result.replaceAll("(?m)\\s*\\'\\'\\'.*$", + "\n---"); - /** - * Override with any special text escaping logic to handle unsafe - * characters so as to avoid code injection. - * - * @param input String to be cleaned up - * @return string with unsafe characters removed or escaped - */ - public String escapeUnsafeCharacters(String input) { + /** + * Remove any trailing new line at the end of the string + */ + result = result.replaceAll("\\s+$", ""); + } + + return result; + } + + @Override + public String escapeQuotationMark(String input) { + return input; + } /** - * Replace backticks with normal single quotes. + * Override with any special text escaping logic to handle unsafe + * characters so as to avoid code injection. + * + * @param input String to be cleaned up + * @return string with unsafe characters removed or escaped */ - String result = input.replaceAll("`", "'"); + public String escapeUnsafeCharacters(String input) { - return result; - } + /** + * Replace backticks with normal single quotes. + */ + String result = input.replaceAll("`", "'"); + return result; + } - @Override - public CodegenOperation fromOperation(String path, String httpMethod, - Operation operation, - Map definitions, - Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, - definitions, swagger); + @Override + public CodegenOperation fromOperation(String path, String httpMethod, + Operation operation, + Map definitions, + OpenAPI openAPI) { - /** - * Check if the operation has a Bash codegen specific description - * for help - */ - if(op.vendorExtensions.containsKey("x-bash-codegen-description")) { - String bash_description - = (String)op.vendorExtensions.get("x-bash-codegen-description"); + CodegenOperation op = super.fromOperation(path, httpMethod, operation, + definitions, openAPI); - op.vendorExtensions.put("x-bash-codegen-description", - escapeText(bash_description)); - } + /** + * Check if the operation has a Bash codegen specific description + * for help + */ + if (op.vendorExtensions.containsKey("x-bash-codegen-description")) { + String bash_description + = (String) op.vendorExtensions.get("x-bash-codegen-description"); - /** - * Check if operation has an 'x-code-samples' vendor extension with - * Shell example - */ - if(op.vendorExtensions.containsKey("x-code-samples")) { + op.vendorExtensions.put("x-bash-codegen-description", + escapeText(bash_description)); + } + + /** + * Check if operation has an 'x-code-samples' vendor extension with + * Shell example + */ + if (op.vendorExtensions.containsKey("x-code-samples")) { - List codesamples = (List)op.vendorExtensions.get("x-code-samples"); + List codesamples = (List) op.vendorExtensions.get("x-code-samples"); - for (Object codesample : codesamples) { - if(codesample instanceof ObjectNode) { - ObjectNode codesample_object = (ObjectNode) codesample; + for (Object codesample : codesamples) { + if (codesample instanceof ObjectNode) { + ObjectNode codesample_object = (ObjectNode) codesample; - if ((codesample_object.get("lang").asText()).equals("Shell")) { + if ((codesample_object.get("lang").asText()).equals("Shell")) { - op.vendorExtensions.put("x-bash-codegen-sample", - escapeUnsafeCharacters( - codesample_object.get("source").asText())); + op.vendorExtensions.put("x-bash-codegen-sample", + escapeUnsafeCharacters( + codesample_object.get("source").asText())); + } } } } - } - for (CodegenParameter p : op.bodyParams) { - if(p.dataType != null && definitions.get(p.dataType) != null) { - /** - * If the operation produces Json and has nonempty example - * try to reformat it. - */ - if(operation.getConsumes() != null - && operation.getConsumes().contains("application/json") - && definitions.get(p.dataType).getExample() != null) { - - ObjectMapper mapper = new ObjectMapper(); - try { - p.vendorExtensions.put( - "x-codegen-body-example", - mapper.writerWithDefaultPrettyPrinter().writeValueAsString( - definitions.get(p.dataType).getExample())); - } - catch(JsonProcessingException e) { - e.printStackTrace(); - } - } - else { - /** - * Otherwise present whatever is provided as example - */ - p.vendorExtensions.put( - "x-codegen-body-example", - definitions.get(p.dataType).getExample()); - } + for (CodegenParameter p : op.bodyParams) { + if (p.dataType != null && definitions.get(p.dataType) != null) { + /** + * If the operation produces Json and has nonempty example + * try to reformat it. + */ + if (getConsumesInfo(operation) != null + && getConsumesInfo(operation).contains("application/json") + && definitions.get(p.dataType).getExample() != null) { + + ObjectMapper mapper = new ObjectMapper(); + try { + p.vendorExtensions.put( + "x-codegen-body-example", + mapper.writerWithDefaultPrettyPrinter().writeValueAsString( + definitions.get(p.dataType).getExample())); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + } else { + /** + * Otherwise present whatever is provided as example + */ + p.vendorExtensions.put( + "x-codegen-body-example", + definitions.get(p.dataType).getExample()); + } + } } - } - return op; + return op; - } + } - /** - * Preprocess original properties from the Swagger definition where necessary. - * - * @param swagger [description] - */ - @Override - public void preprocessSwagger(Swagger swagger) { - super.preprocessSwagger(swagger); + /** + * Preprocess original properties from the OpenAPI definition where necessary. + * + * @param openAPI [description] + */ + @Override + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); - if ("/".equals(swagger.getBasePath())) { - swagger.setBasePath(""); + /* TODO need to revise the logic below + if ("/".equals(openAPI.getServers())) { + openAPI.setBasePath(""); } + */ - if(swagger.getInfo() != null - && swagger.getInfo().getVendorExtensions()!=null) { + /* there should not be a need to get the vendor extension this way + if(openAPI.getInfo() != null + && openAPI.getInfo().getVendorExtensions()!=null) { String bash_codegen_app_description - = (String)swagger.getInfo().getVendorExtensions() + = (String)openAPI.getInfo().getVendorExtensions() .get("x-bash-codegen-description"); - if(bash_codegen_app_description != null) { - + if (bash_codegen_app_description != null) { bash_codegen_app_description = escapeText(bash_codegen_app_description); @@ -691,73 +663,72 @@ public void preprocessSwagger(Swagger swagger) { bash_codegen_app_description); } - } - - } + }*/ + } - @Override - public void setParameterExampleValue(CodegenParameter p) { - String example; + @Override + public void setParameterExampleValue(CodegenParameter p) { + String example; - if (p.defaultValue == null) { - example = p.example; - } else { - example = p.defaultValue; - } + if (p.defaultValue == null) { + example = p.example; + } else { + example = p.defaultValue; + } - String type = p.baseType; - if (type == null) { - type = p.dataType; - } + String type = p.baseType; + if (type == null) { + type = p.dataType; + } - if ("string".equalsIgnoreCase(type)) { - if (example == null) { - example = p.paramName + "_example"; - } - example = "'" + escapeText(example) + "'"; - } else if ("integer".equals(type)) { - if (example == null) { - example = "56"; - } - } else if ("float".equalsIgnoreCase(type)) { - if (example == null) { - example = "3.4"; - } - } else if ("boolean".equalsIgnoreCase(type)) { - if (example == null) { - example = "True"; - } - } else if ("file".equalsIgnoreCase(type)) { - if (example == null) { - example = "/path/to/file"; - } - example = "'" + escapeText(example) + "'"; - } else if ("date".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20"; - } - example = "'" + escapeText(example) + "'"; - } else if ("datetime".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20T19:20:30+01:00"; - } - example = "'" + escapeText(example) + "'"; - } else if (!languageSpecificPrimitives.contains(type)) { - // type is a model class, e.g. User - example = type; - } else { - LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); - } + if ("string".equalsIgnoreCase(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "'" + escapeText(example) + "'"; + } else if ("integer".equals(type)) { + if (example == null) { + example = "56"; + } + } else if ("float".equalsIgnoreCase(type)) { + if (example == null) { + example = "3.4"; + } + } else if ("boolean".equalsIgnoreCase(type)) { + if (example == null) { + example = "True"; + } + } else if ("file".equalsIgnoreCase(type)) { + if (example == null) { + example = "/path/to/file"; + } + example = "'" + escapeText(example) + "'"; + } else if ("date".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20"; + } + example = "'" + escapeText(example) + "'"; + } else if ("datetime".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20T19:20:30+01:00"; + } + example = "'" + escapeText(example) + "'"; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + example = type; + } else { + LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); + } - if (example == null) { - example = "NULL"; - } else if (Boolean.TRUE.equals(p.isListContainer)) { - example = "[" + example + "]"; - } else if (Boolean.TRUE.equals(p.isMapContainer)) { - example = "{'key': " + example + "}"; - } + if (example == null) { + example = "NULL"; + } else if (Boolean.TRUE.equals(p.isListContainer)) { + example = "[" + example + "]"; + } else if (Boolean.TRUE.equals(p.isMapContainer)) { + example = "{'key': " + example + "}"; + } - p.example = example; - } + p.example = example; + } } 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 71bebee65faf..548ed1617061 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 @@ -2,10 +2,18 @@ import com.google.common.collect.ImmutableMap; import com.samskivert.mustache.Mustache; + import org.openapitools.codegen.*; -import io.swagger.models.Model; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.utils.*; +import org.openapitools.codegen.mustache.*; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.core.util.Yaml; +import io.swagger.v3.parser.util.SchemaTypeUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,7 +52,6 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { protected boolean supportsUWP = Boolean.FALSE; protected boolean netStandard = Boolean.FALSE; protected boolean generatePropertyChanged = Boolean.FALSE; - protected boolean hideGenerationTimestamp = Boolean.TRUE; protected boolean validatable = Boolean.TRUE; protected Map regexModifiers; @@ -62,6 +69,8 @@ public CSharpClientCodegen() { modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); + hideGenerationTimestamp = Boolean.TRUE; + cliOptions.clear(); // CLI options @@ -188,12 +197,6 @@ public void processOpts() { setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); } - // default HIDE_GENERATION_TIMESTAMP to true - if (additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - setHideGenerationTimestamp(convertPropertyToBooleanAndWriteBack(CodegenConstants.HIDE_GENERATION_TIMESTAMP)); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, hideGenerationTimestamp); - } if (isEmpty(apiPackage)) { setApiPackage("Api"); @@ -504,10 +507,10 @@ public void setOptionalAssemblyInfoFlag(boolean flag) { } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); if (allDefinitions != null && codegenModel != null && codegenModel.parent != null) { - final Model parentModel = allDefinitions.get(toModelName(codegenModel.parent)); + final Schema parentModel = allDefinitions.get(toModelName(codegenModel.parent)); if (parentModel != null) { final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); if (codegenModel.hasEnums) { @@ -580,11 +583,10 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } /* - * The swagger pattern spec follows the Perl convention and style of modifiers. .NET + * The pattern spec follows the Perl convention and style of modifiers. .NET * does not support this syntax directly so we need to convert the pattern to a .NET compatible * format and apply modifiers in a compatible way. * See https://msdn.microsoft.com/en-us/library/yd1hzczs(v=vs.110).aspx for .NET options. - * See https://github.com/swagger-api/swagger-codegen/pull/2794 for Python's initial implementation from which this is copied. */ public void postProcessPattern(String pattern, Map vendorExtensions) { if (pattern != null) { @@ -768,10 +770,6 @@ public void setGeneratePropertyChanged(final Boolean generatePropertyChanged) { this.generatePropertyChanged = generatePropertyChanged; } - public void setHideGenerationTimestamp(boolean hideGenerationTimestamp) { - this.hideGenerationTimestamp = hideGenerationTimestamp; - } - public boolean isNonPublicApi() { return nonPublicApi; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpDotNet2ClientCodegen.java similarity index 93% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpDotNet2ClientCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpDotNet2ClientCodegen.java index d5505299d744..2c6673aafc92 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpDotNet2ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpDotNet2ClientCodegen.java @@ -1,19 +1,15 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.SupportingFile; - +import org.openapitools.codegen.*; import java.io.File; -public class CsharpDotNet2ClientCodegen extends AbstractCSharpCodegen { +public class CSharpDotNet2ClientCodegen extends AbstractCSharpCodegen { public static final String CLIENT_PACKAGE = "clientPackage"; protected String clientPackage = "IO.Swagger.Client"; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; - public CsharpDotNet2ClientCodegen() { + public CSharpDotNet2ClientCodegen() { super(); // clear import mapping (from default generator) as C# (2.0) does not use it diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NancyFXServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java similarity index 80% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NancyFXServerCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java index 11986d4b4b9d..e6c9c51c1a3c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NancyFXServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java @@ -1,23 +1,19 @@ package org.openapitools.codegen.languages; import static com.google.common.base.Strings.isNullOrEmpty; +import static org.apache.commons.lang3.StringUtils.capitalize; import static org.openapitools.codegen.CodegenConstants.*; import static org.openapitools.codegen.CodegenType.SERVER; import static java.util.Arrays.asList; import static java.util.UUID.randomUUID; -import static org.apache.commons.lang3.StringUtils.capitalize; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.SupportingFile; -import org.openapitools.codegen.utils.ModelUtils; -import io.swagger.models.Swagger; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.*; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; import java.io.File; +import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -38,8 +34,8 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; -public class NancyFXServerCodegen extends AbstractCSharpCodegen { - private static final Logger log = LoggerFactory.getLogger(NancyFXServerCodegen.class); +public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen { + private static final Logger LOGGER = LoggerFactory.getLogger(CSharpNancyFXServerCodegen.class); private static final String API_NAMESPACE = "Modules"; private static final String MODEL_NAMESPACE = "Models"; @@ -48,8 +44,8 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { private static final String PACKAGE_CONTEXT = "packageContext"; private static final String ASYNC_SERVER = "asyncServer"; - private static final Map> propertyToSwaggerTypeMapping = - createPropertyToSwaggerTypeMapping(); + private static final Map> propertyToOpenAPITypeMapping = + createPropertyToOpenAPITypeMapping(); private String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}"; @@ -58,10 +54,12 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { private final Multimap childrenByParent = ArrayListMultimap.create(); private final BiMap modelNameMapping = HashBiMap.create(); - /** If set to true, we will generate c# async endpoints and service interfaces */ + /** + * If set to true, we will generate c# async endpoints and service interfaces + */ private boolean asyncServer = false; - public NancyFXServerCodegen() { + public CSharpNancyFXServerCodegen() { outputFolder = "generated-code" + File.separator + getName(); apiTemplateFiles.put("api.mustache", ".cs"); @@ -70,7 +68,7 @@ public NancyFXServerCodegen() { // contextually reserved words setReservedWordsLowerCase( - asList("var", "async", "await", "dynamic", "yield") + asList("var", "async", "await", "dynamic", "yield") ); cliOptions.clear(); @@ -80,7 +78,7 @@ public NancyFXServerCodegen() { addOption(PACKAGE_VERSION, "C# package version.", packageVersion); addOption(SOURCE_FOLDER, SOURCE_FOLDER_DESC, sourceFolder); addOption(INTERFACE_PREFIX, INTERFACE_PREFIX_DESC, interfacePrefix); - addOption(OPTIONAL_PROJECT_GUID,OPTIONAL_PROJECT_GUID_DESC, null); + addOption(OPTIONAL_PROJECT_GUID, OPTIONAL_PROJECT_GUID_DESC, null); addOption(PACKAGE_CONTEXT, "Optionally overrides the PackageContext which determines the namespace (namespace=packageName.packageContext). If not set, packageContext will default to basePath.", null); // CLI Switches @@ -105,19 +103,19 @@ public CodegenType getTag() { @Override public String getName() { - return "nancyfx"; + return "csharp-nancyfx"; } @Override public String getHelp() { - return "Generates a NancyFX Web API server."; + return "Generates a C# NancyFX Web API server."; } @Override public void processOpts() { super.processOpts(); - apiPackage = isNullOrEmpty(packageName) ? API_NAMESPACE : packageName + "." + API_NAMESPACE; + apiPackage = isNullOrEmpty(packageName) ? API_NAMESPACE : packageName + "." + API_NAMESPACE; modelPackage = isNullOrEmpty(packageName) ? MODEL_NAMESPACE : packageName + "." + MODEL_NAMESPACE; supportingFiles.add(new SupportingFile("parameters.mustache", sourceFile("Utils"), "Parameters.cs")); @@ -129,7 +127,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln")); supportingFiles.add(new SupportingFile("Project.mustache", sourceFolder(), packageName + ".csproj")); } - + if (additionalProperties.containsKey(OPTIONAL_PROJECT_GUID)) { setPackageGuid((String) additionalProperties.get(OPTIONAL_PROJECT_GUID)); } @@ -150,10 +148,10 @@ public void processOpts() { private void setupModelTemplate() { final Object immutableOption = additionalProperties.get(IMMUTABLE_OPTION); if (immutableOption != null && "false".equalsIgnoreCase(immutableOption.toString())) { - log.info("Using mutable model template"); + LOGGER.info("Using mutable model template"); modelTemplateFiles.put("modelMutable.mustache", ".cs"); } else { - log.info("Using immutable model template"); + LOGGER.info("Using immutable model template"); modelTemplateFiles.put("model.mustache", ".cs"); } } @@ -170,18 +168,18 @@ private void processImportedMappings() { final String assemblyFramework = namespaceInfo.length > 3 ? namespaceInfo[3].trim() : "net45"; if (isNullOrEmpty(model) || isNullOrEmpty(namespaceName)) { - log.warn(String.format("Could not import: '%s' - invalid namespace: '%s'", model, entry.getValue())); + LOGGER.warn(String.format("Could not import: '%s' - invalid namespace: '%s'", model, entry.getValue())); importMapping.remove(model); } else { - log.info(String.format("Importing: '%s' from '%s' namespace.", model, namespaceName)); + LOGGER.info(String.format("Importing: '%s' from '%s' namespace.", model, namespaceName)); importMapping.put(model, namespaceName); } if (!isNullOrEmpty(modelClass)) { - log.info(String.format("Mapping: '%s' class to '%s'", model, modelClass)); + LOGGER.info(String.format("Mapping: '%s' class to '%s'", model, modelClass)); modelNameMapping.put(model, modelClass); } if (assembly != null && assemblyVersion != null) { - log.info(String.format("Adding dependency: '%s', version: '%s', framework: '%s'", + LOGGER.info(String.format("Adding dependency: '%s', version: '%s', framework: '%s'", assembly, assemblyVersion, assemblyVersion)); dependencies.put(assembly, new DependencyInfo(assemblyVersion, assemblyFramework)); } @@ -239,13 +237,13 @@ protected void processOperation(final CodegenOperation operation) { @Override public Map postProcessAllModels(final Map models) { - final Map processed = super.postProcessAllModels(models); + final Map processed = super.postProcessAllModels(models); postProcessParentModels(models); return processed; } private void postProcessParentModels(final Map models) { - log.debug("Processing parents: " + parentModels); + LOGGER.debug("Processing parents: " + parentModels); for (final String parent : parentModels) { final CodegenModel parentModel = ModelUtils.getModelByName(parent, models); parentModel.hasChildren = true; @@ -265,7 +263,7 @@ private void processParentPropertiesInChildModel(final CodegenModel parent, fina for (final CodegenProperty property : parent.vars) { final CodegenProperty duplicatedByParent = childPropertiesByName.get(property.name); if (duplicatedByParent != null) { - log.info(String.format("Property: '%s' in '%s' model is inherited from '%s'" , + LOGGER.info(String.format("Property: '%s' in '%s' model is inherited from '%s'", property.name, child.classname, parent.classname)); duplicatedByParent.isInherited = true; final CodegenProperty parentVar = duplicatedByParent.clone(); @@ -298,16 +296,16 @@ public String toEnumVarName(final String name, final String datatype) { final String enumName = camelize( sanitizeName(name) - .replaceFirst("^_", "") - .replaceFirst("_$", "") - .replaceAll("-", "_")); + .replaceFirst("^_", "") + .replaceFirst("_$", "") + .replaceAll("-", "_")); final String result; if (enumName.matches("\\d.*")) { result = "_" + enumName; } else { result = enumName; } - log.debug(String.format("toEnumVarName('%s', %s) = '%s'", name, datatype, enumName)); + LOGGER.debug(String.format("toEnumVarName('%s', %s) = '%s'", name, datatype, enumName)); return result; } @@ -319,7 +317,7 @@ public String toApiName(final String name) { } else { apiName = capitalize(name); } - log.debug(String.format("toApiName('%s') = '%s'", name, apiName)); + LOGGER.debug(String.format("toApiName('%s') = '%s'", name, apiName)); return apiName; } @@ -334,13 +332,13 @@ public String toModelImport(final String name) { if (modelNameMapping.containsValue(name)) { final String modelName = modelNameMapping.inverse().get(name); result = importMapping.containsKey(modelName) ? - importMapping.get(modelName) : super.toModelImport(name); + importMapping.get(modelName) : super.toModelImport(name); } else if (importMapping.containsKey(name)) { result = importMapping.get(name); } else { result = null; } - log.debug(String.format("toModelImport('%s') = '%s'", name, result)); + LOGGER.debug(String.format("toModelImport('%s') = '%s'", name, result)); return result; } @@ -348,15 +346,20 @@ public String toModelImport(final String name) { public String toModelName(final String name) { final String modelName = super.toModelName(name); final String mappedModelName = modelNameMapping.get(modelName); - return isNullOrEmpty(mappedModelName) ? modelName: mappedModelName; + return isNullOrEmpty(mappedModelName) ? modelName : mappedModelName; } @Override - public void preprocessSwagger(final Swagger swagger) { + public void preprocessOpenAPI(final OpenAPI openAPI) { + URL url = URLPathUtils.getServerURL(openAPI); + String path = "/"; + if (url != null) { + path = url.getPath(); + } final String packageContextOption = (String) additionalProperties.get(PACKAGE_CONTEXT); - additionalProperties.put("packageContext", packageContextOption == null ? sanitizeName(swagger.getBasePath()) : packageContextOption); + additionalProperties.put("packageContext", packageContextOption == null ? sanitizeName(path) : packageContextOption); final Object basePathOption = additionalProperties.get(USE_BASE_PATH); - additionalProperties.put("baseContext", basePathOption == null ? swagger.getBasePath() : "/"); + additionalProperties.put("baseContext", basePathOption == null ? path : "/"); } @Override @@ -365,26 +368,26 @@ public String toEnumName(final CodegenProperty property) { } @Override - public String getSwaggerType(final Property property) { - for (Entry> entry : propertyToSwaggerTypeMapping.entrySet()) { + public String getSchemaType(final Schema property) { + for (Entry> entry : propertyToOpenAPITypeMapping.entrySet()) { if (entry.getValue().apply(property)) { return entry.getKey(); } } - return super.getSwaggerType(property); + return super.getSchemaType(property); } - private static Map> createPropertyToSwaggerTypeMapping() { - final ImmutableMap.Builder> mapping = ImmutableMap.builder(); + private static Map> createPropertyToOpenAPITypeMapping() { + final ImmutableMap.Builder> mapping = ImmutableMap.builder(); mapping.put("time", timeProperty()); return mapping.build(); } - private static Predicate timeProperty() { - return new Predicate() { + private static Predicate timeProperty() { + return new Predicate() { @Override - public boolean apply(Property property) { - return property instanceof StringProperty && "time".equalsIgnoreCase(property.getFormat()); + public boolean apply(Schema property) { + return ModelUtils.isStringSchema(property) && "time".equalsIgnoreCase(property.getFormat()); } }; } @@ -397,7 +400,7 @@ private static Map nodaTimeTypesMappings() { } private static Set nodaTimePrimitiveTypes() { - return ImmutableSet.of("LocalTime?", "LocalDate?","ZonedDateTime?"); + return ImmutableSet.of("LocalTime?", "LocalDate?", "ZonedDateTime?"); } private class DependencyInfo { @@ -405,7 +408,7 @@ private class DependencyInfo { private final String framework; private DependencyInfo(final String version, final String framework) { - this.version = version; + this.version = version; this.framework = framework; } } 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 7983a42d82d2..7fc9bb5d4d4d 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 @@ -7,10 +7,11 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.Contact; -import io.swagger.models.Info; -import io.swagger.models.License; -import io.swagger.models.Swagger; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.info.*; + import org.apache.commons.lang3.StringUtils; import java.io.File; @@ -71,8 +72,8 @@ public String getHelp() { } @Override - public void preprocessSwagger(Swagger swagger) { - super.preprocessSwagger(swagger); + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); if (additionalProperties.containsKey(PROJECT_NAME)) { projectName = ((String) additionalProperties.get(PROJECT_NAME)); @@ -87,9 +88,9 @@ public void preprocessSwagger(Swagger swagger) { baseNamespace = ((String) additionalProperties.get(BASE_NAMESPACE)); } - if (swagger.getInfo() != null) { - Info info = swagger.getInfo(); - if (projectName == null && info.getTitle() != null) { + if (openAPI.getInfo() != null) { + Info info = openAPI.getInfo(); + if (projectName == null && info.getTitle() != null) { // when projectName is not specified, generate it from info.title projectName = dashize(info.getTitle()); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiCodegen.java similarity index 82% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiGenerator.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiCodegen.java index 27b0c6b5e232..85848bc21c29 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiCodegen.java @@ -1,23 +1,24 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -public class ConfluenceWikiGenerator extends DefaultCodegen implements CodegenConfig { +public class ConfluenceWikiCodegen extends DefaultCodegen implements CodegenConfig { private static final String ALL_OPERATIONS = ""; protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; - public ConfluenceWikiGenerator() { + public ConfluenceWikiCodegen() { super(); outputFolder = "docs"; embeddedTemplateDir = templateDir = "confluenceWikiDocs"; @@ -34,7 +35,7 @@ public ConfluenceWikiGenerator() { cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC)); - + additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appDescription", "A sample swagger server"); additionalProperties.put("infoUrl", "https://helloreverb.com"); @@ -69,16 +70,14 @@ public String getHelp() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PistacheServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java similarity index 71% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PistacheServerCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java index 970e29be6570..8b2fb6ee6438 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PistacheServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java @@ -1,6 +1,5 @@ package org.openapitools.codegen.languages; - import java.io.File; import java.util.Arrays; import java.util.HashMap; @@ -9,34 +8,18 @@ import java.util.Map; import java.util.Set; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenParameter; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.SupportingFile; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Response; -import io.swagger.models.Swagger; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BaseIntegerProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DecimalProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FileProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; - -public class PistacheServerCodegen extends AbstractCppCodegen { +import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.core.util.Yaml; + +public class CppPistacheServerCodegen extends AbstractCppCodegen { protected String implFolder = "impl"; @Override @@ -46,7 +29,7 @@ public CodegenType getTag() { @Override public String getName() { - return "pistache-server"; + return "cpp-pistache-server"; } @Override @@ -54,7 +37,7 @@ public String getHelp() { return "Generates a C++ API server (based on Pistache)"; } - public PistacheServerCodegen() { + public CppPistacheServerCodegen() { super(); apiPackage = "io.swagger.server.api"; @@ -137,7 +120,7 @@ public String toModelImport(String name) { } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); Set oldImports = codegenModel.imports; @@ -154,17 +137,18 @@ public CodegenModel fromModel(String name, Model model, Map allDe @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, - Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + Map definitions, OpenAPI openAPI) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, openAPI); if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { - Response methodResponse = findMethodResponse(operation.getResponses()); + ApiResponse apiResponse = findMethodResponse(operation.getResponses()); - if (methodResponse != null) { - if (methodResponse.getSchema() != null) { - CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); + if (apiResponse != null) { + Schema response = getSchemaFromResponse(apiResponse); + if (response != null) { + CodegenProperty cm = fromProperty("response", response); op.vendorExtensions.put("x-codegen-response", cm); - if(cm.datatype == "HttpContent") { + if (cm.datatype == "HttpContent") { op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); } } @@ -196,7 +180,7 @@ public Map postProcessOperations(Map objs) { op.bodyParam.vendorExtensions.put("x-codegen-pistache-isStringOrDate", op.bodyParam.isString || op.bodyParam.isDate); } - if(op.consumes != null) { + if (op.consumes != null) { for (Map consume : op.consumes) { if (consume.get("mediaType") != null && consume.get("mediaType").equals("application/json")) { consumeJson = true; @@ -206,17 +190,17 @@ public Map postProcessOperations(Map objs) { op.httpMethod = op.httpMethod.substring(0, 1).toUpperCase() + op.httpMethod.substring(1).toLowerCase(); - for(CodegenParameter param : op.allParams){ - if (param.isFormParam) isParsingSupported=false; - if (param.isFile) isParsingSupported=false; - if (param.isCookieParam) isParsingSupported=false; + for (CodegenParameter param : op.allParams) { + if (param.isFormParam) isParsingSupported = false; + if (param.isFile) isParsingSupported = false; + if (param.isCookieParam) isParsingSupported = false; //TODO: This changes the info about the real type but it is needed to parse the header params if (param.isHeaderParam) { param.dataType = "Optional"; param.baseType = "Optional"; - } else if(param.isQueryParam){ - if(param.isPrimitiveType) { + } else if (param.isQueryParam) { + if (param.isPrimitiveType) { param.dataType = "Optional<" + param.dataType + ">"; } else { param.dataType = "Optional<" + param.baseType + ">"; @@ -244,15 +228,15 @@ public String toModelFilename(String name) { public String apiFilename(String templateName, String tag) { String result = super.apiFilename(templateName, tag); - if ( templateName.endsWith("impl-header.mustache") ) { + if (templateName.endsWith("impl-header.mustache")) { int ix = result.lastIndexOf('/'); result = result.substring(0, ix) + result.substring(ix, result.length() - 2) + "Impl.h"; result = result.replace(apiFileFolder(), implFileFolder()); - } else if ( templateName.endsWith("impl-source.mustache") ) { + } else if (templateName.endsWith("impl-source.mustache")) { int ix = result.lastIndexOf('/'); result = result.substring(0, ix) + result.substring(ix, result.length() - 4) + "Impl.cpp"; result = result.replace(apiFileFolder(), implFileFolder()); - } else if ( templateName.endsWith("api-server.mustache") ) { + } else if (templateName.endsWith("api-server.mustache")) { int ix = result.lastIndexOf('/'); result = result.substring(0, ix) + result.substring(ix, result.length() - 4) + "MainServer.cpp"; result = result.replace(apiFileFolder(), outputFolder); @@ -271,66 +255,65 @@ public String toApiFilename(String name) { * for different property types * * @return a string value used as the `dataType` field for model templates, - * `returnType` for api templates + * `returnType` for api templates */ @Override - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); + public String getTypeDeclaration(Schema p) { + String openAPIType = getSchemaType(p); - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; } - if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; + if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + ""; } - if (p instanceof StringProperty || p instanceof DateProperty - || p instanceof DateTimeProperty || p instanceof FileProperty - || languageSpecificPrimitives.contains(swaggerType)) { - return toModelName(swaggerType); + if (ModelUtils.isStringSchema(p) + || ModelUtils.isDateSchema(p) + || ModelUtils.isDateTimeSchema(p) || ModelUtils.isFileSchema(p) + || languageSpecificPrimitives.contains(openAPIType)) { + return toModelName(openAPIType); } - return "std::shared_ptr<" + swaggerType + ">"; + return "std::shared_ptr<" + openAPIType + ">"; } @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "\"\""; - } else if (p instanceof BooleanProperty) { + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { return "false"; - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { return "\"\""; - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { return "\"\""; - } else if (p instanceof DoubleProperty) { + } else if (ModelUtils.isNumberSchema(p)) { + if (ModelUtils.isFloatSchema(p)) { + return "0.0f"; + } return "0.0"; - } else if (p instanceof FloatProperty) { - return "0.0f"; - } else if (p instanceof LongProperty) { - return "0L"; - } else if (p instanceof IntegerProperty || p instanceof BaseIntegerProperty) { + } else if (ModelUtils.isIntegerSchema(p)) { + if (ModelUtils.isLongSchema(p)) { + return "0L"; + } return "0"; - } else if (p instanceof DecimalProperty) { - return "0.0"; - } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); + } else if (ModelUtils.isMapSchema(p)) { + String inner = getSchemaType((Schema) p.getAdditionalProperties()); return "std::map()"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); if (!languageSpecificPrimitives.contains(inner)) { inner = "std::shared_ptr<" + inner + ">"; } return "std::vector<" + inner + ">()"; - } else if (p instanceof RefProperty) { - RefProperty rp = (RefProperty) p; - return "new " + toModelName(rp.getSimpleRef()) + "()"; + } else if (!StringUtils.isEmpty(p.get$ref())) { // model + return "new " + toModelName(getSimpleRef(p.get$ref())) + "()"; + } else if (ModelUtils.isStringSchema(p)) { + return "\"\""; } + return "nullptr"; } @@ -370,22 +353,21 @@ private String implFileFolder() { /** * Optional - swagger type conversion. This is used to map swagger types in - * a `Property` into either language specific types via `typeMapping` or + * a `Schema` into either language specific types via `typeMapping` or * into complex models if there is not a mapping. * * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property */ @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) return toModelName(type); } else - type = swaggerType; + type = openAPIType; return toModelName(type); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Qt5CPPGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java similarity index 76% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Qt5CPPGenerator.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java index 1188755639e3..27678ade427c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Qt5CPPGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java @@ -1,20 +1,14 @@ package org.openapitools.codegen.languages; +import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DecimalProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.BaseIntegerProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.parser.util.SchemaTypeUtil; import java.io.File; import java.util.Arrays; @@ -23,9 +17,10 @@ import java.util.Map; import java.util.Set; -public class Qt5CPPGenerator extends AbstractCppCodegen implements CodegenConfig { +public class CppQt5ClientCodegen extends AbstractCppCodegen implements CodegenConfig { public static final String CPP_NAMESPACE = "cppNamespace"; public static final String CPP_NAMESPACE_DESC = "C++ namespace (convention: name::space::for::api)."; + public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate client.pri."; protected final String PREFIX = "SWG"; protected Set foundationClasses = new HashSet(); @@ -35,8 +30,9 @@ public class Qt5CPPGenerator extends AbstractCppCodegen implements CodegenConfig protected Map namespaces = new HashMap(); protected Set systemIncludes = new HashSet(); protected String cppNamespace = "Swagger"; + protected boolean optionalProjectFileFlag = true; - public Qt5CPPGenerator() { + public CppQt5ClientCodegen() { super(); // set the output folder here @@ -82,6 +78,7 @@ public Qt5CPPGenerator() { // CLI options addOption(CPP_NAMESPACE, CPP_NAMESPACE_DESC, this.cppNamespace); + addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE, OPTIONAL_PROJECT_FILE_DESC, this.optionalProjectFileFlag); /* * Additional Properties. These values can be passed to the templates and @@ -93,7 +90,7 @@ public Qt5CPPGenerator() { // Write defaults namespace in properties so that it can be accessible in templates. // At this point command line has not been parsed so if value is given // in command line it will superseed this content - additionalProperties.put("cppNamespace",cppNamespace); + additionalProperties.put("cppNamespace", cppNamespace); /* * Language Specific Primitives. These types will not trigger imports by @@ -114,6 +111,10 @@ public Qt5CPPGenerator() { supportingFiles.add(new SupportingFile("HttpRequest.cpp.mustache", sourceFolder, PREFIX + "HttpRequest.cpp")); supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h")); supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); + supportingFiles.add(new SupportingFile("QObjectWrapper.h.mustache", sourceFolder, PREFIX + "QObjectWrapper.h")); + if (optionalProjectFileFlag) { + supportingFiles.add(new SupportingFile("Project.mustache", sourceFolder, "client.pri")); + } super.typeMapping = new HashMap(); @@ -128,8 +129,8 @@ public Qt5CPPGenerator() { typeMapping.put("file", "SWGHttpRequestInputFileElement"); typeMapping.put("object", PREFIX + "Object"); //TODO binary should be mapped to byte array - // mapped to String as a workaround - typeMapping.put("binary", "QString"); + // mapped as "file" type for OAS 3.0 + typeMapping.put("binary", "SWGHttpRequestInputFileElement"); typeMapping.put("ByteArray", "QByteArray"); // UUID support - possible enhancement : use QUuid instead of QString. // beware though that Serialisation/deserialisation of QUuid does not @@ -153,23 +154,16 @@ public Qt5CPPGenerator() { systemIncludes.add("QByteArray"); } - protected void addOption(String key, String description, String defaultValue) { - CliOption option = new CliOption(key, description); - if (defaultValue != null) - option.defaultValue(defaultValue); - cliOptions.add(option); - } - @Override public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("cppNamespace")){ + if (additionalProperties.containsKey("cppNamespace")) { cppNamespace = (String) additionalProperties.get("cppNamespace"); } additionalProperties.put("cppNamespaceDeclarations", cppNamespace.split("\\::")); - if(additionalProperties.containsKey("modelNamePrefix")){ + if (additionalProperties.containsKey("modelNamePrefix")) { supportingFiles.clear(); supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, modelNamePrefix + "Helpers.h")); supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, modelNamePrefix + "Helpers.cpp")); @@ -177,12 +171,19 @@ public void processOpts() { supportingFiles.add(new SupportingFile("HttpRequest.cpp.mustache", sourceFolder, modelNamePrefix + "HttpRequest.cpp")); supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, modelNamePrefix + "ModelFactory.h")); supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, modelNamePrefix + "Object.h")); + supportingFiles.add(new SupportingFile("QObjectWrapper.h.mustache", sourceFolder, modelNamePrefix + "QObjectWrapper.h")); typeMapping.put("object", modelNamePrefix + "Object"); typeMapping.put("file", modelNamePrefix + "HttpRequestInputFileElement"); importMapping.put("SWGHttpRequestInputFileElement", "#include \"" + modelNamePrefix + "HttpRequest.h\""); additionalProperties().put("prefix", modelNamePrefix); } + + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_FILE)) { + setOptionalProjectFileFlag(convertPropertyToBooleanAndWriteBack(CodegenConstants.OPTIONAL_PROJECT_FILE)); + } else { + additionalProperties.put(CodegenConstants.OPTIONAL_PROJECT_FILE, optionalProjectFileFlag); + } } /** @@ -204,7 +205,7 @@ public CodegenType getTag() { */ @Override public String getName() { - return "qt5cpp"; + return "cpp-qt5"; } /** @@ -215,7 +216,7 @@ public String getName() { */ @Override public String getHelp() { - return "Generates a qt5 C++ client library."; + return "Generates a Qt5 C++ client library."; } @Override @@ -241,7 +242,7 @@ public String toModelImport(String name) { */ @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -282,82 +283,71 @@ public String toApiFilename(String name) { * @return a string value used as the `dataType` field for model templates, `returnType` for api templates */ @Override - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">*"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "*"; + public String getTypeDeclaration(Schema p) { + String openAPIType = getSchemaType(p); + + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">*"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "*"; } - if (foundationClasses.contains(swaggerType)) { - return swaggerType + "*"; - } else if (languageSpecificPrimitives.contains(swaggerType)) { - return toModelName(swaggerType); + if (foundationClasses.contains(openAPIType)) { + return openAPIType + "*"; + } else if (languageSpecificPrimitives.contains(openAPIType)) { + return toModelName(openAPIType); } else { - return swaggerType + "*"; + return openAPIType + "*"; } } - @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "new QString(\"\")"; - } else if (p instanceof BooleanProperty) { + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { return "false"; - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { return "NULL"; - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { return "NULL"; - } else if (p instanceof DoubleProperty) { + } else if (ModelUtils.isNumberSchema(p)) { + if (SchemaTypeUtil.FLOAT_FORMAT.equals(p.getFormat())) { + return "0.0f"; + } return "0.0"; - } else if (p instanceof FloatProperty) { - return "0.0f"; - } else if (p instanceof IntegerProperty) { - return "0"; - } else if (p instanceof LongProperty) { - return "0L"; - } else if (p instanceof BaseIntegerProperty) { - // catchall for any other format of the swagger specifiction - // integer type not explicitly handled above + } else if (ModelUtils.isIntegerSchema(p)) { + if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) { + return "0L"; + } return "0"; - } else if (p instanceof DecimalProperty) { - return "0.0"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return "new QMap()"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return "new QList<" + getTypeDeclaration(inner) + ">()"; - } - // else - if (p instanceof RefProperty) { - RefProperty rp = (RefProperty) p; - return "new " + toModelName(rp.getSimpleRef()) + "()"; + } else if (ModelUtils.isStringSchema(p)) { + return "new QString(\"\")"; + } else if (!StringUtils.isEmpty(p.get$ref())) { + return "new " + toModelName(getSimpleRef(p.get$ref())) + "()"; } return "NULL"; } /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * Optional - swagger type conversion. This is used to map swagger types in a `Schema` into * either language specific types via `typeMapping` or into complex models if there is not a mapping. * * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property */ @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) { return toModelName(type); } @@ -365,7 +355,7 @@ public String getSwaggerType(Property p) { return type; } } else { - type = swaggerType; + type = openAPIType; } return toModelName(type); } @@ -425,4 +415,8 @@ public String escapeQuotationMark(String input) { public String escapeUnsafeCharacters(String input) { return input.replace("*/", "*_/").replace("/*", "/_*"); } + + public void setOptionalProjectFileFlag(boolean flag) { + this.optionalProjectFileFlag = flag; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestClientCodegen.java index 9467045bf5f8..f98630d11820 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestClientCodegen.java @@ -12,6 +12,7 @@ import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; +import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.CodegenModel; @@ -21,25 +22,12 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.SupportingFile; import org.openapitools.codegen.utils.ModelUtils; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Response; -import io.swagger.models.Swagger; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BaseIntegerProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DecimalProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FileProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.parser.util.SchemaTypeUtil; + public class CppRestClientCodegen extends AbstractCppCodegen { @@ -70,7 +58,7 @@ public CodegenType getTag() { * @return the friendly name for the generator */ public String getName() { - return "cpprest"; + return "cpp-restsdk"; } /** @@ -160,13 +148,6 @@ public CppRestClientCodegen() { importMapping.put("utility::datetime", "#include "); } - protected void addOption(String key, String description, String defaultValue) { - CliOption option = new CliOption(key, description); - if (defaultValue != null) - option.defaultValue(defaultValue); - cliOptions.add(option); - } - @Override public void processOpts() { super.processOpts(); @@ -216,7 +197,7 @@ public String toModelImport(String name) { } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); Set oldImports = codegenModel.imports; @@ -233,18 +214,18 @@ public CodegenModel fromModel(String name, Model model, Map allDe @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, - Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + Map schema, OpenAPI openAPI) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, schema, openAPI); if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { - Response methodResponse = findMethodResponse(operation.getResponses()); + ApiResponse methodResponse = findMethodResponse(operation.getResponses()); if (methodResponse != null) { - if (methodResponse.getSchema() != null) { - CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); + Schema response = getSchemaFromResponse(methodResponse); + if (response != null) { + CodegenProperty cm = fromProperty("response", response); op.vendorExtensions.put("x-codegen-response", cm); - if(cm.datatype == "HttpContent") - { + if (cm.datatype == "HttpContent") { op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); } } @@ -256,7 +237,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { - if (isFileProperty(property)) { + if (isFileSchema(property)) { property.vendorExtensions.put("x-codegen-file", true); } @@ -268,7 +249,7 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } } - protected boolean isFileProperty(CodegenProperty property) { + protected boolean isFileSchema(CodegenProperty property) { return property.baseType.equals("HttpContent"); } @@ -288,65 +269,61 @@ public String toApiFilename(String name) { * for different property types * * @return a string value used as the `dataType` field for model templates, - * `returnType` for api templates + * `returnType` for api templates */ @Override - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } - if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; - } - if (p instanceof StringProperty || p instanceof DateProperty - || p instanceof DateTimeProperty || p instanceof FileProperty - || languageSpecificPrimitives.contains(swaggerType)) { - return toModelName(swaggerType); + public String getTypeDeclaration(Schema p) { + String openAPIType = getSchemaType(p); + + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + ""; + } else if (ModelUtils.isStringSchema(p) + || ModelUtils.isDateSchema(p) || ModelUtils.isDateTimeSchema(p) + || ModelUtils.isFileSchema(p) + || languageSpecificPrimitives.contains(openAPIType)) { + return toModelName(openAPIType); } - return "std::shared_ptr<" + swaggerType + ">"; + return "std::shared_ptr<" + openAPIType + ">"; } @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "utility::conversions::to_string_t(\"\")"; - } else if (p instanceof BooleanProperty) { + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { return "false"; - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { return "utility::datetime()"; - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { return "utility::datetime()"; - } else if (p instanceof DoubleProperty) { + } else if (ModelUtils.isNumberSchema(p)) { + if (ModelUtils.isFloatSchema(p)) { + return "0.0f"; + } return "0.0"; - } else if (p instanceof FloatProperty) { - return "0.0f"; - } else if (p instanceof LongProperty) { - return "0L"; - } else if (p instanceof IntegerProperty || p instanceof BaseIntegerProperty) { + } else if (ModelUtils.isIntegerSchema(p)) { + if (ModelUtils.isLongSchema(p)) { + return "0L"; + } return "0"; - } else if (p instanceof DecimalProperty) { - return "0.0"; - } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); + } else if (ModelUtils.isMapSchema(p)) { + String inner = getSchemaType((Schema) p.getAdditionalProperties()); return "std::map()"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); if (!languageSpecificPrimitives.contains(inner)) { inner = "std::shared_ptr<" + inner + ">"; } return "std::vector<" + inner + ">()"; - } else if (p instanceof RefProperty) { - RefProperty rp = (RefProperty) p; - return "new " + toModelName(rp.getSimpleRef()) + "()"; + } else if (!StringUtils.isEmpty(p.get$ref())) { + return "new " + toModelName(getSimpleRef(p.get$ref())) + "()"; + } else if (ModelUtils.isStringSchema(p)) { + return "utility::conversions::to_string_t(\"\")"; } return "nullptr"; } @@ -366,22 +343,22 @@ public void postProcessParameter(CodegenParameter parameter) { /** * Optional - swagger type conversion. This is used to map swagger types in - * a `Property` into either language specific types via `typeMapping` or + * a `Schema` into either language specific types via `typeMapping` or * into complex models if there is not a mapping. * * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property + * @see io.swagger.v3.oas.models.media.Schema */ @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) return toModelName(type); } else - type = swaggerType; + type = openAPIType; return toModelName(type); } @@ -415,7 +392,7 @@ public String escapeUnsafeCharacters(String input) { @Override public Map postProcessAllModels(final Map models) { - final Map processed = super.postProcessAllModels(models); + final Map processed = super.postProcessAllModels(models); postProcessParentModels(models); return processed; } @@ -435,11 +412,11 @@ private void postProcessParentModels(final Map models) { */ private void processParentPropertiesInChildModel(final CodegenModel parent, final CodegenModel child) { final Map childPropertiesByName = new HashMap<>(child.vars.size()); - for (final CodegenProperty childProperty : child.vars) { - childPropertiesByName.put(childProperty.name, childProperty); + for (final CodegenProperty childSchema : child.vars) { + childPropertiesByName.put(childSchema.name, childSchema); } - for (final CodegenProperty parentProperty : parent.vars) { - final CodegenProperty duplicatedByParent = childPropertiesByName.get(parentProperty.name); + for (final CodegenProperty parentSchema : parent.vars) { + final CodegenProperty duplicatedByParent = childPropertiesByName.get(parentSchema.name); if (duplicatedByParent != null) { duplicatedByParent.isInherited = true; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java new file mode 100644 index 000000000000..b545545e0bcd --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java @@ -0,0 +1,382 @@ +package org.openapitools.codegen.languages; + +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.Map; +import java.util.Set; + +import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.core.util.Yaml; + +public class CppRestbedServerCodegen extends AbstractCppCodegen { + + public static final String DECLSPEC = "declspec"; + public static final String DEFAULT_INCLUDE = "defaultInclude"; + + protected String packageVersion = "1.0.0"; + protected String declspec = ""; + protected String defaultInclude = ""; + + public CppRestbedServerCodegen() { + super(); + + apiPackage = "io.swagger.server.api"; + modelPackage = "io.swagger.server.model"; + + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-source.mustache", ".cpp"); + + apiTemplateFiles.put("api-header.mustache", ".h"); + apiTemplateFiles.put("api-source.mustache", ".cpp"); + + embeddedTemplateDir = templateDir = "restbed"; + + cliOptions.clear(); + + // CLI options + addOption(CodegenConstants.MODEL_PACKAGE, "C++ namespace for models (convention: name.space.model).", + this.modelPackage); + addOption(CodegenConstants.API_PACKAGE, "C++ namespace for apis (convention: name.space.api).", + this.apiPackage); + addOption(CodegenConstants.PACKAGE_VERSION, "C++ package version.", this.packageVersion); + addOption(DECLSPEC, "C++ preprocessor to place before the class name for handling dllexport/dllimport.", + this.declspec); + addOption(DEFAULT_INCLUDE, + "The default include statement that should be placed in all headers for including things like the declspec (convention: #include \"Commons.h\" ", + this.defaultInclude); + + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList("int", "char", "bool", "long", "float", "double", "int32_t", "int64_t")); + + typeMapping = new HashMap(); + typeMapping.put("date", "std::string"); + typeMapping.put("DateTime", "std::string"); + typeMapping.put("string", "std::string"); + typeMapping.put("integer", "int32_t"); + typeMapping.put("long", "int64_t"); + typeMapping.put("boolean", "bool"); + typeMapping.put("array", "std::vector"); + typeMapping.put("map", "std::map"); + typeMapping.put("file", "std::string"); + typeMapping.put("object", "Object"); + typeMapping.put("binary", "restbed::Bytes"); + typeMapping.put("number", "double"); + typeMapping.put("UUID", "std::string"); + + super.importMapping = new HashMap(); + importMapping.put("std::vector", "#include "); + importMapping.put("std::map", "#include "); + importMapping.put("std::string", "#include "); + importMapping.put("Object", "#include \"Object.h\""); + importMapping.put("restbed::Bytes", "#include "); + } + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + */ + public CodegenType getTag() { + return CodegenType.SERVER; + } + + /** + * Configures a friendly name for the generator. This will be used by the + * generator to select the library with the -l flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "cpp-restbed-server"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with + * help tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a C++ API Server with Restbed (https://github.com/Corvusoft/restbed)."; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(DECLSPEC)) { + declspec = additionalProperties.get(DECLSPEC).toString(); + } + + if (additionalProperties.containsKey(DEFAULT_INCLUDE)) { + defaultInclude = additionalProperties.get(DEFAULT_INCLUDE).toString(); + } + + additionalProperties.put("modelNamespaceDeclarations", modelPackage.split("\\.")); + additionalProperties.put("modelNamespace", modelPackage.replaceAll("\\.", "::")); + additionalProperties.put("apiNamespaceDeclarations", apiPackage.split("\\.")); + additionalProperties.put("apiNamespace", apiPackage.replaceAll("\\.", "::")); + additionalProperties.put("declspec", declspec); + additionalProperties.put("defaultInclude", defaultInclude); + } + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle + * escaping those terms here. This logic is only called if a variable + * matches the reserved words + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + /** + * Location to write model files. You can use the modelPackage() as defined + * when the class is instantiated + */ + public String modelFileFolder() { + return (outputFolder + "/model").replace("/", File.separator); + } + + /** + * Location to write api files. You can use the apiPackage() as defined when + * the class is instantiated + */ + @Override + public String apiFileFolder() { + return (outputFolder + "/api").replace("/", File.separator); + } + + @Override + public String toModelImport(String name) { + if (importMapping.containsKey(name)) { + return importMapping.get(name); + } else { + return "#include \"" + name + ".h\""; + } + } + + @Override + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); + + Set oldImports = codegenModel.imports; + codegenModel.imports = new HashSet(); + for (String imp : oldImports) { + String newImp = toModelImport(imp); + if (!newImp.isEmpty()) { + codegenModel.imports.add(newImp); + } + } + + return codegenModel; + } + + + @Override + public String toModelFilename(String name) { + return initialCaps(name); + } + + @Override + public String toApiFilename(String name) { + return initialCaps(name) + "Api"; + } + + @SuppressWarnings("unchecked") + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + List newOpList = new ArrayList(); + for (CodegenOperation op : operationList) { + String path = new String(op.path); + + String[] items = path.split("/", -1); + String resourceNameCamelCase = ""; + op.path = ""; + for (String item : items) { + if (item.length() > 1) { + if (item.matches("^\\{(.*)\\}$")) { + String tmpResourceName = item.substring(1, item.length() - 1); + resourceNameCamelCase += Character.toUpperCase(tmpResourceName.charAt(0)) + tmpResourceName.substring(1); + item = item.substring(0, item.length() - 1); + item += ": .*}"; + } else { + resourceNameCamelCase += Character.toUpperCase(item.charAt(0)) + item.substring(1); + } + } else if (item.length() == 1) { + resourceNameCamelCase += Character.toUpperCase(item.charAt(0)); + } + op.path += item + "/"; + } + op.vendorExtensions.put("x-codegen-resourceName", resourceNameCamelCase); + boolean foundInNewList = false; + for (CodegenOperation op1 : newOpList) { + if (!foundInNewList) { + if (op1.path.equals(op.path)) { + foundInNewList = true; + List currentOtherMethodList = (List) op1.vendorExtensions.get("x-codegen-otherMethods"); + if (currentOtherMethodList == null) { + currentOtherMethodList = new ArrayList(); + } + op.operationIdCamelCase = op1.operationIdCamelCase; + currentOtherMethodList.add(op); + op1.vendorExtensions.put("x-codegen-otherMethods", currentOtherMethodList); + } + } + } + if (!foundInNewList) { + newOpList.add(op); + } + } + operations.put("operation", newOpList); + return objs; + } + + /** + * Optional - type declaration. This is a String which is used by the + * templates to instantiate your types. There is typically special handling + * for different property types + * + * @return a string value used as the `dataType` field for model templates, + * `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Schema p) { + String openAPIType = getSchemaType(p); + + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + ""; + } else if (ModelUtils.isStringSchema(p) + || ModelUtils.isDateSchema(p) + || ModelUtils.isDateTimeSchema(p) || ModelUtils.isFileSchema(p) + || languageSpecificPrimitives.contains(openAPIType)) { + return toModelName(openAPIType); + } + + return "std::shared_ptr<" + openAPIType + ">"; + } + + @Override + public String toDefaultValue(Schema p) { + if (ModelUtils.isStringSchema(p)) { + return "\"\""; + } else if (ModelUtils.isBooleanSchema(p)) { + return "false"; + } else if (ModelUtils.isDateSchema(p)) { + return "\"\""; + } else if (ModelUtils.isDateTimeSchema(p)) { + return "\"\""; + } else if (ModelUtils.isNumberSchema(p)) { + if (ModelUtils.isFloatSchema(p)) { + return "0.0f"; + } + return "0.0"; + } else if (ModelUtils.isIntegerSchema(p)) { + if (ModelUtils.isLongSchema(p)) { + return "0L"; + } + return "0"; + } else if (ModelUtils.isMapSchema(p)) { + String inner = getSchemaType((Schema) p.getAdditionalProperties()); + return "std::map()"; + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); + if (!languageSpecificPrimitives.contains(inner)) { + inner = "std::shared_ptr<" + inner + ">"; + } + return "std::vector<" + inner + ">()"; + } else if (!StringUtils.isEmpty(p.get$ref())) { + return "new " + toModelName(getSimpleRef(p.get$ref())) + "()"; + } + return "nullptr"; + } + + @Override + public void postProcessParameter(CodegenParameter parameter) { + super.postProcessParameter(parameter); + + boolean isPrimitiveType = parameter.isPrimitiveType == Boolean.TRUE; + boolean isListContainer = parameter.isListContainer == Boolean.TRUE; + boolean isString = parameter.isString == Boolean.TRUE; + + if (!isPrimitiveType && !isListContainer && !isString && !parameter.dataType.startsWith("std::shared_ptr")) { + parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">"; + } + } + + /** + * Optional - swagger type conversion. This is used to map swagger types in + * a `Schema` into either language specific types via `typeMapping` or + * into complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + */ + @Override + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); + String type = null; + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); + if (languageSpecificPrimitives.contains(type)) + return toModelName(type); + } else + type = openAPIType; + return toModelName(type); + } + + @Override + public String toModelName(String type) { + if (typeMapping.keySet().contains(type) || typeMapping.values().contains(type) + || importMapping.values().contains(type) || defaultIncludes.contains(type) + || languageSpecificPrimitives.contains(type)) { + return type; + } else { + return Character.toUpperCase(type.charAt(0)) + type.substring(1); + } + } + + @Override + public String toApiName(String type) { + return Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api"; + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TizenClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java similarity index 78% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TizenClientCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java index a534cc1b9061..038f7720a28c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TizenClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java @@ -1,22 +1,17 @@ package org.openapitools.codegen.languages; +import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DecimalProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.parser.util.SchemaTypeUtil; import java.io.File; import java.util.Arrays; @@ -26,12 +21,12 @@ import java.util.Set; -public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig { +public class CppTizenClientCodegen extends DefaultCodegen implements CodegenConfig { protected static String PREFIX = "ArtikCloud"; protected String sourceFolder = "src"; protected String documentationFolder = "doc"; - public TizenClientCodegen() { + public CppTizenClientCodegen() { super(); outputFolder = ""; modelTemplateFiles.put("model-header.mustache", ".h"); @@ -120,7 +115,7 @@ public CodegenType getTag() { @Override public String getName() { - return "tizen"; + return "cpp-tizen"; } @Override @@ -129,10 +124,10 @@ public String getHelp() { } @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { + public String toInstantiationType(Schema p) { + if (ModelUtils.isMapSchema(p)) { return instantiationTypes.get("map"); - } else if (p instanceof ArrayProperty) { + } else if (ModelUtils.isArraySchema(p)) { return instantiationTypes.get("array"); } else { return null; @@ -149,27 +144,27 @@ public String getTypeDeclaration(String name) { } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) { return toModelName(type); } } else { - type = swaggerType; + type = openAPIType; } return toModelName(type); } @Override - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - if (languageSpecificPrimitives.contains(swaggerType)) { - return toModelName(swaggerType); + public String getTypeDeclaration(Schema p) { + String openAPIType = getSchemaType(p); + if (languageSpecificPrimitives.contains(openAPIType)) { + return toModelName(openAPIType); } else { - return swaggerType + ""; + return openAPIType + ""; } } @@ -200,30 +195,30 @@ public String toModelImport(String name) { //Might not be needed @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "std::string()"; - } else if (p instanceof BooleanProperty) { + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { return "bool(false)"; - } else if (p instanceof DoubleProperty) { + } else if (ModelUtils.isNumberSchema(p)) { + if (SchemaTypeUtil.FLOAT_FORMAT.equals(p.getFormat())) { + return "float(0)"; + } return "double(0)"; - } else if (p instanceof FloatProperty) { - return "float(0)"; - } else if (p instanceof IntegerProperty) { + + } else if (ModelUtils.isIntegerSchema(p)) { + if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) { + return "long(0)"; + } return "int(0)"; - } else if (p instanceof LongProperty) { - return "long(0)"; - } else if (p instanceof DecimalProperty) { - return "long(0)"; - } else if (p instanceof MapProperty) { + } else if (ModelUtils.isMapSchema(p)) { return "new std::map()"; - } else if (p instanceof ArrayProperty) { + } else if (ModelUtils.isArraySchema(p)) { return "new std::list()"; - } - // else - if (p instanceof RefProperty) { - RefProperty rp = (RefProperty) p; - return "new " + toModelName(rp.getSimpleRef()) + "()"; + } else if (!StringUtils.isEmpty(p.get$ref())) { + return "new " + toModelName(getSimpleRef(p.get$ref())) + "()"; + } else if (ModelUtils.isDateSchema(p) || ModelUtils.isDateTimeSchema(p)) { + return "null"; + } else if (ModelUtils.isStringSchema(p)) { + return "std::string()"; } return "null"; } @@ -265,8 +260,8 @@ public String toVarName(String name) { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -275,7 +270,7 @@ public String escapeReservedWord(String name) { @Override public String toOperationId(String operationId) { // throw exception if method name is empty - if (operationId=="") { + if (operationId == "") { throw new RuntimeException("Empty method name (operationId) not allowed"); } @@ -288,4 +283,15 @@ public String toOperationId(String operationId) { return camelize(operationId, true); } + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + } 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 2b4f9c62bd5e..c3e9e74a3220 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 @@ -8,10 +8,9 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.Model; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.media.*; import java.io.File; import java.util.ArrayList; @@ -62,7 +61,7 @@ public DartClientCodegen() { "is", "library", "new", "null", "operator", "part", "rethrow", "return", "set", "static", "super", "switch", "sync*", "this", "throw", "true", "try", "typedef", "var", "void", "while", - "with", "yield", "yield*" ) + "with", "yield", "yield*") ); languageSpecificPrimitives = new HashSet( @@ -165,14 +164,6 @@ public void processOpts() { this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - // make api and model doc path available in mustache template additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); @@ -275,41 +266,40 @@ public String toApiFilename(String name) { } @Override - public String toDefaultValue(Property p) { - if (p instanceof MapProperty) { + public String toDefaultValue(Schema p) { + if (ModelUtils.isMapSchema(p)) { return "{}"; - } else if (p instanceof ArrayProperty) { + } else if (ModelUtils.isArraySchema(p)) { return "[]"; } return super.toDefaultValue(p); } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + ""; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + + return getSchemaType(p) + ""; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) { return type; } } else { - type = swaggerType; + type = openAPIType; } return toModelName(type); } @@ -417,12 +407,12 @@ public String toEnumVarName(String value, String datatype) { @Override public String toEnumValue(String value, String datatype) { - if ("number".equalsIgnoreCase(datatype) || - "int".equalsIgnoreCase(datatype)) { - return value; - } else { - return "\"" + escapeText(value) + "\""; - } + if ("number".equalsIgnoreCase(datatype) || + "int".equalsIgnoreCase(datatype)) { + return value; + } else { + return "\"" + escapeText(value) + "\""; + } } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java index aa5a1eb77b16..729d1b153866 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java @@ -8,10 +8,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.*; +import org.openapitools.codegen.mustache.*; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; public class EiffelClientCodegen extends AbstractEiffelCodegen { static Logger LOGGER = LoggerFactory.getLogger(EiffelClientCodegen.class); @@ -52,20 +56,15 @@ public EiffelClientCodegen() { apiTestTemplateFiles.put("test/api_test.mustache", ".e"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); embeddedTemplateDir = templateDir = "Eiffel"; + + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = true; } @Override public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } else { @@ -157,7 +156,7 @@ public void setPackageName(String packageName) { public void setPackageVersion(String packageVersion) { this.packageVersion = packageVersion; } - + @Override public String toEnumName(CodegenProperty property) { @@ -177,7 +176,7 @@ public String toEnumVarName(String value, String datatype) { // number if ("INTEGER_32".equals(datatype) || "INTEGER_64".equals(datatype) || - "REAL_32".equals(datatype) || "REAL_64".equals(datatype)) { + "REAL_32".equals(datatype) || "REAL_64".equals(datatype)) { String varName = "NUMBER_" + value; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); @@ -189,7 +188,7 @@ public String toEnumVarName(String value, String datatype) { String var = value.replaceAll("\\W+", "_").toLowerCase(); if (var.matches("\\d.*")) { return "val_" + var; - } else if (var.startsWith("_")){ + } else if (var.startsWith("_")) { return "val" + var; } else { return "val_" + var; @@ -199,11 +198,11 @@ public String toEnumVarName(String value, String datatype) { @Override public String toEnumValue(String value, String datatype) { if ("INTEGER_32".equals(datatype) || "INTEGER_64".equals(datatype) || - "REAL_32".equals(datatype) || "REAL_64".equals(datatype)) { + "REAL_32".equals(datatype) || "REAL_64".equals(datatype)) { return value; } else { return "\"" + escapeText(value) + "\""; } - } + } } 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 6ba17d8407c4..7b23d31a2547 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 @@ -3,10 +3,12 @@ import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; import org.openapitools.codegen.*; -import io.swagger.models.properties.*; -import io.swagger.models.Info; -import io.swagger.models.Model; -import io.swagger.models.Swagger; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.media.*; + import org.apache.commons.lang3.StringUtils; import java.io.IOException; @@ -125,7 +127,7 @@ public ElixirClientCodegen() { "Tuple", "PID", "DateTime" - ) + ) ); // ref: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types @@ -209,15 +211,15 @@ public void execute(Template.Fragment fragment, Writer writer) throws IOExceptio } @Override - public void preprocessSwagger(Swagger swagger) { - Info info = swagger.getInfo(); - if (moduleName == null) { - if (info.getTitle() != null) { - // default to the appName (from title field) - setModuleName(modulized(escapeText(info.getTitle()))); - } else { - setModuleName(defaultModuleName); - } + public void preprocessOpenAPI(OpenAPI openAPI) { + Info info = openAPI.getInfo(); + if (moduleName == null) { + if (info.getTitle() != null) { + // default to the appName (from title field) + setModuleName(modulized(escapeText(info.getTitle()))); + } else { + setModuleName(defaultModuleName); + } } additionalProperties.put("moduleName", moduleName); @@ -226,17 +228,17 @@ public void preprocessSwagger(Swagger swagger) { } supportingFiles.add(new SupportingFile("connection.ex.mustache", - sourceFolder(), - "connection.ex")); + sourceFolder(), + "connection.ex")); supportingFiles.add(new SupportingFile("request_builder.ex.mustache", - sourceFolder(), - "request_builder.ex")); + sourceFolder(), + "request_builder.ex")); supportingFiles.add(new SupportingFile("deserializer.ex.mustache", - sourceFolder(), - "deserializer.ex")); + sourceFolder(), + "deserializer.ex")); } @Override @@ -279,7 +281,7 @@ public Map postProcessOperations(Map objs) { } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel cm = super.fromModel(name, model, allDefinitions); return new ExtendedCodegenModel(cm); } @@ -416,99 +418,64 @@ public String toOperationId(String operationId) { * @return a string value used as the `dataType` field for model templates, `returnType` for api templates */ @Override - public String getTypeDeclaration(Property p) { - // SubClasses of AbstractProperty - // - // ArrayProperty - // MapProperty - // PasswordProperty - // StringProperty - // EmailProperty - // ByteArrayProperty - // DateProperty - // UUIDProperty - // DateTimeProperty - // ObjectProperty - // AbstractNumericProperty - // BaseIntegerProperty - // IntegerProperty - // LongProperty - // DecimalProperty - // DoubleProperty - // FloatProperty - // BinaryProperty - // BooleanProperty - // RefProperty - // FileProperty - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return "%{optional(String.t) => " + getTypeDeclaration(inner) + "}"; - } else if (p instanceof PasswordProperty) { + } else if (ModelUtils.isPasswordSchema(p)) { return "String.t"; - } else if (p instanceof EmailProperty) { + } else if (ModelUtils.isEmailSchema(p)) { return "String.t"; - } else if (p instanceof ByteArrayProperty) { + } else if (ModelUtils.isByteArraySchema(p)) { return "binary()"; - } else if (p instanceof StringProperty) { + } else if (ModelUtils.isUUIDSchema(p)) { return "String.t"; - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { return "Date.t"; - } else if (p instanceof UUIDProperty) { - return "String.t"; - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { return "DateTime.t"; - } else if (p instanceof ObjectProperty) { + } else if (ModelUtils.isObjectSchema(p)) { // How to map it? return super.getTypeDeclaration(p); - } else if (p instanceof IntegerProperty) { - return "integer()"; - } else if (p instanceof LongProperty) { + } else if (ModelUtils.isIntegerSchema(p)) { return "integer()"; - } else if (p instanceof BaseIntegerProperty) { - return "integer()"; - } else if (p instanceof DoubleProperty) { - return "float()"; - } else if (p instanceof FloatProperty) { - return "float()"; - } else if (p instanceof DecimalProperty) { + } else if (ModelUtils.isNumberSchema(p)) { return "float()"; - } else if (p instanceof AbstractNumericProperty) { - return "number()"; - } else if (p instanceof BinaryProperty) { + } else if (ModelUtils.isBinarySchema(p)) { return "binary()"; - } else if (p instanceof BooleanProperty) { + } else if (ModelUtils.isBooleanSchema(p)) { return "boolean()"; - } else if (p instanceof RefProperty) { + } else if (!StringUtils.isEmpty(p.get$ref())) { // model // How to map it? return super.getTypeDeclaration(p); - } else if (p instanceof FileProperty) { + } else if (ModelUtils.isFileSchema(p)) { + return "String.t"; + } else if (ModelUtils.isStringSchema(p)) { return "String.t"; } return super.getTypeDeclaration(p); } /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * Optional - swagger type conversion. This is used to map swagger types in a `Schema` into * either language specific types via `typeMapping` or into complex models if there is not a mapping. * * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property */ @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) return toModelName(type); } else - type = swaggerType; + type = openAPIType; return toModelName(type); } @@ -662,8 +629,11 @@ private void buildTypespec(CodegenParameter param, StringBuilder sb) { sb.append(".t"); } } + private void buildTypespec(CodegenProperty property, StringBuilder sb) { - if (property.isListContainer) { + if (property == null) { + LOGGER.warn("CodegenProperty cannot be null"); + } else if (property.isListContainer) { sb.append("list("); buildTypespec(property.items, sb); sb.append(")"); @@ -709,6 +679,7 @@ public String decodedStruct() { class ExtendedCodegenModel extends CodegenModel { public boolean hasImports; + public ExtendedCodegenModel(CodegenModel cm) { super(); @@ -755,7 +726,7 @@ public ExtendedCodegenModel(CodegenModel cm) { this.isArrayModel = cm.isArrayModel; this.hasChildren = cm.hasChildren; this.hasOnlyReadOnly = cm.hasOnlyReadOnly; - this.externalDocs = cm.externalDocs; + this.externalDocumentation = cm.externalDocumentation; this.vendorExtensions = cm.vendorExtensions; this.additionalPropertiesType = cm.additionalPropertiesType; 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 d3dd23307d53..0237059f67c9 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 @@ -1,29 +1,14 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenParameter; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenResponse; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.SupportingFile; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.Response; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.ModelUtils; +import org.openapitools.codegen.languages.features.BeanValidationFeatures; +import org.openapitools.codegen.languages.features.JbossFeature; +import org.openapitools.codegen.languages.features.SwaggerFeatures; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.oas.models.responses.*; import java.io.File; import java.text.Collator; @@ -72,36 +57,36 @@ public ElmClientCodegen() { supportsInheritance = true; reservedWords = new HashSet<>( - Arrays.asList( - "if", "then", "else", - "case", "of", - "let", "in", - "type", - "module", "where", - "import", "exposing", - "as", - "port") + Arrays.asList( + "if", "then", "else", + "case", "of", + "let", "in", + "type", + "module", "where", + "import", "exposing", + "as", + "port") ); defaultIncludes = new HashSet<>( - Arrays.asList( - "List") + Arrays.asList( + "List") ); languageSpecificPrimitives = new HashSet<>( - Arrays.asList( - "Bool", - "Dict", - "Float", - "Int", - "String") + Arrays.asList( + "Bool", + "Dict", + "Float", + "Int", + "String") ); customPrimitives = new HashSet<>( - Arrays.asList( - "Byte", - "DateOnly", - "DateTime") + Arrays.asList( + "Byte", + "DateOnly", + "DateTime") ); instantiationTypes.clear(); @@ -185,10 +170,10 @@ public String toEnumVarName(String value, String datatype) { } @Override - public String toInstantiationType(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); + public String toInstantiationType(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); return instantiationTypes.get("array") + " " + inner; } else { return null; @@ -211,20 +196,19 @@ public String modelFileFolder() { } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { - CodegenModel m = super.fromModel(name, model, allDefinitions); + public CodegenModel fromModel(String name, Schema schema, Map allDefinitions) { + CodegenModel m = super.fromModel(name, schema, allDefinitions); - if (model instanceof ArrayModel) { - ArrayModel am = (ArrayModel) model; - ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); - CodegenProperty codegenProperty = fromProperty(name, arrayProperty); + if (ModelUtils.isArraySchema(schema)) { + ArraySchema am = (ArraySchema) schema; + CodegenProperty codegenProperty = fromProperty(name, (Schema) am.getItems()); m.vendorExtensions.putAll(codegenProperty.vendorExtensions); } return m; } - @SuppressWarnings({ "static-method", "unchecked" }) + @SuppressWarnings({"static-method", "unchecked"}) public Map postProcessAllModels(Map objs) { // Index all CodegenModels by model name. Map allModels = new HashMap<>(); @@ -301,7 +285,7 @@ public int compare(CodegenModel cm1, CodegenModel cm2) { elmImports.add(elmImport); // set discriminator value to all children (recursively) - this.setDiscriminatorValue(child, cm.discriminator, this.getDiscriminatorValue(child)); + this.setDiscriminatorValue(child, cm.getDiscriminatorName(), this.getDiscriminatorValue(child)); // add all non-discriminator vars int index = 0; @@ -339,7 +323,7 @@ private void setDiscriminatorValue(CodegenModel model, String baseName, String v private String getDiscriminatorValue(CodegenModel model) { return model.vendorExtensions.containsKey(X_DISCRIMINATOR_TYPE) ? - (String) model.vendorExtensions.get(X_DISCRIMINATOR_TYPE) : model.classname; + (String) model.vendorExtensions.get(X_DISCRIMINATOR_TYPE) : model.classname; } private ElmImport createPropertyImport(final CodegenProperty property) { @@ -364,7 +348,7 @@ public Map postProcessModels(Map objs) { } @Override - @SuppressWarnings({ "static-method", "unchecked" }) + @SuppressWarnings({"static-method", "unchecked"}) public Map postProcessOperations(Map operations) { Map objs = (Map) operations.get("operations"); List ops = (List) objs.get("operation"); @@ -374,7 +358,7 @@ public Map postProcessOperations(Map operations) for (CodegenOperation op : ops) { String path = op.path; for (CodegenParameter param : op.pathParams) { - final String var = param.isString ? param.paramName : "toString " + param.paramName; + final String var = param.isString ? param.paramName : "toString " + param.paramName; path = path.replace("{" + param.paramName + "}", "\" ++ " + var + " ++ \""); } op.path = ("\"" + path + "\"").replaceAll(" \\+\\+ \"\"", ""); @@ -415,45 +399,30 @@ public Map postProcessOperations(Map operations) } @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty sp = (StringProperty) p; - if (sp.getDefault() != null) { - return toOptionalValue("\"" + sp.getDefault().toString() + "\""); + public String toDefaultValue(Schema p) { + if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return toOptionalValue("\"" + p.getDefault().toString() + "\""); } return toOptionalValue(null); - } else if (p instanceof BooleanProperty) { - BooleanProperty bp = (BooleanProperty) p; - if (bp.getDefault() != null) { - return toOptionalValue(bp.getDefault() ? "True" : "False"); + } else if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + return toOptionalValue(Boolean.valueOf(p.getDefault().toString()) ? "True" : "False"); } return toOptionalValue(null); - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { return toOptionalValue(null); - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { return toOptionalValue(null); - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; + } else if (ModelUtils.isNumberSchema(p)) { + NumberSchema dp = (NumberSchema) p; if (dp.getDefault() != null) { return toOptionalValue(dp.getDefault().toString()); } return toOptionalValue(null); - } else if (p instanceof FloatProperty) { - FloatProperty fp = (FloatProperty) p; - if (fp.getDefault() != null) { - return toOptionalValue(fp.getDefault().toString()); - } - return toOptionalValue(null); - } else if (p instanceof IntegerProperty) { - IntegerProperty ip = (IntegerProperty) p; - if (ip.getDefault() != null) { - return toOptionalValue(ip.getDefault().toString()); - } - return toOptionalValue(null); - } else if (p instanceof LongProperty) { - LongProperty lp = (LongProperty) p; - if (lp.getDefault() != null) { - return toOptionalValue(lp.getDefault().toString()); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return toOptionalValue(p.getDefault().toString()); } return toOptionalValue(null); } else { @@ -469,8 +438,8 @@ private String toOptionalValue(String value) { } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String swaggerType = super.getSchemaType(p); String type; if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); @@ -483,21 +452,20 @@ public String getSwaggerType(Property p) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return getTypeDeclaration(inner); - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return getTypeDeclaration(inner); } return super.getTypeDeclaration(p); } @Override - public CodegenProperty fromProperty(String name, Property p) { + public CodegenProperty fromProperty(String name, Schema p) { final CodegenProperty property = super.fromProperty(name, p); final String dataType = property.isEnum ? property.baseName : property.datatype; @@ -510,7 +478,7 @@ public CodegenProperty fromProperty(String name, Property p) { } @Override - public CodegenResponse fromResponse(String responseCode, Response resp) { + public CodegenResponse fromResponse(String responseCode, ApiResponse resp) { final CodegenResponse response = super.fromResponse(responseCode, resp); if (response.dataType != null) { addEncoderAndDecoder(response.vendorExtensions, response.dataType, response.primitiveType); 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 a23d3889792b..1cb413dda004 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 @@ -1,12 +1,14 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.*; + import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.parameters.Parameter; + +import org.openapitools.codegen.*; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.core.util.Json; import java.io.File; import java.util.*; @@ -95,25 +97,25 @@ public String getTypeDeclaration(String name) { } @Override - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - if (typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); + public String getTypeDeclaration(Schema p) { + String schemaType = getSchemaType(p); + if (typeMapping.containsKey(schemaType)) { + return typeMapping.get(schemaType); } - return swaggerType; + return schemaType; } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if(typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); if(languageSpecificPrimitives.contains(type)) return (type); } else - type = getTypeDeclaration(toModelName(snakeCase(swaggerType))); + type = getTypeDeclaration(toModelName(snakeCase(schemaType))); return type; } 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 741caa5c6d8f..0db208ad5bd8 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 @@ -9,8 +9,9 @@ import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import org.openapitools.codegen.*; -import io.swagger.models.*; -import io.swagger.util.Json; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -122,7 +123,7 @@ public ErlangServerCodegen() { supportingFiles.add(new SupportingFile("server.mustache", "", toSourceFilePath("server", "erl"))); supportingFiles.add(new SupportingFile("utils.mustache", "", toSourceFilePath("utils", "erl"))); supportingFiles.add(new SupportingFile("auth.mustache", "", toSourceFilePath("auth", "erl"))); - supportingFiles.add(new SupportingFile("swagger.mustache", "", toPrivFilePath("swagger", "json"))); + supportingFiles.add(new SupportingFile("swagger.mustache", "", toPrivFilePath("openapi", "json"))); supportingFiles.add(new SupportingFile("default_logic_handler.mustache", "", toSourceFilePath("default_logic_handler", "erl"))); supportingFiles.add(new SupportingFile("logic_handler.mustache", "", toSourceFilePath("logic_handler", "erl"))); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); @@ -233,14 +234,7 @@ public Map postProcessOperations(Map objs) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { - try { - objs.put("swagger-json", Json.pretty().writeValueAsString(swagger).replace("\r\n", "\n")); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } + generateJSONSpecFile(objs); return super.postProcessSupportingFileData(objs); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FinchServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FinchServerCodegen.java index d17cf6cf7162..468bfab17dfc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FinchServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FinchServerCodegen.java @@ -1,10 +1,23 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.*; -import io.swagger.models.Model; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenSecurity; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.parser.util.SchemaTypeUtil; import java.io.File; import java.util.Arrays; @@ -193,22 +206,19 @@ public String modelFileFolder() { } /** - * Convert Swagger Model object to Codegen Model object + * Convert OpenAPI Model object to Codegen Model object * * @param name the name of the model - * @param model Swagger Model object - * @param allDefinitions a map of all Swagger models from the spec + * @param model OpenAPI Model object + * @param allDefinitions a map of all OpenAPI models from the spec * @return Codegen Model object */ @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); return codegenModel; } - - - @Override public Map postProcessOperations(Map objs) { Map operations = (Map) objs.get("operations"); @@ -236,31 +246,30 @@ public Map postProcessOperations(Map objs) { @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + + return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); if (languageSpecificPrimitives.contains(type)) { return toModelName(type); } } else { - type = swaggerType; + type = schemaType; } return toModelName(type); } @@ -282,7 +291,6 @@ public void setPackageName(String packageName) { /** - * * @param prim * @param isRequired * @param canBeOptional @@ -291,19 +299,19 @@ public void setPackageName(String packageName) { private String toPrimitive(String prim, Boolean isRequired, Boolean canBeOptional) { String converter = ".map(_.to" + prim + ")"; - return (canBeOptional ? (isRequired ? converter : ".map(_" + converter +")") : ""); + return (canBeOptional ? (isRequired ? converter : ".map(_" + converter + ")") : ""); } //All path parameters are String initially, for primitives these need to be converted - private String toPathParameter(CodegenParameter p, String paramType, Boolean canBeOptional ) { + private String toPathParameter(CodegenParameter p, String paramType, Boolean canBeOptional) { Boolean isNotAString = !p.dataType.equals("String"); - return paramType + (canBeOptional && !p.required ? "Option" : "") + "(\""+ p.baseName + "\")" + (isNotAString ? toPrimitive(p.dataType,p.required,canBeOptional) : "") ; + return paramType + (canBeOptional && !p.required ? "Option" : "") + "(\"" + p.baseName + "\")" + (isNotAString ? toPrimitive(p.dataType, p.required, canBeOptional) : ""); } - private String toInputParameter(CodegenParameter p){ - return (p.required ? "" : "Option[")+p.dataType+(p.required ? "" : "]"); + private String toInputParameter(CodegenParameter p) { + return (p.required ? "" : "Option[") + p.dataType + (p.required ? "" : "]"); } private String concat(String original, String addition, String op) { @@ -312,30 +320,30 @@ private String concat(String original, String addition, String op) { // a, b private String csvConcat(String original, String addition) { - return concat(original, addition,", "); + return concat(original, addition, ", "); } + // a :: b private String colConcat(String original, String addition) { - return concat(original, addition," :: "); + return concat(original, addition, " :: "); } private void authParameters(CodegenOperation op) { - String authParams = ""; String authInputParams = ""; String typedAuthInputParams = ""; //Append apikey security to path params and create input parameters for functions - if(op.authMethods != null){ + if (op.authMethods != null) { - for(CodegenSecurity s : op.authMethods) { - if(s.isApiKey && s.isKeyInHeader){ - authParams = colConcat(authParams, "header(\""+ s.keyParamName + "\")"); - } else if(s.isApiKey && s.isKeyInQuery){ - authParams = colConcat(authParams, "param(\""+ s.keyParamName + "\")"); + for (CodegenSecurity s : op.authMethods) { + if (s.isApiKey && s.isKeyInHeader) { + authParams = colConcat(authParams, "header(\"" + s.keyParamName + "\")"); + } else if (s.isApiKey && s.isKeyInQuery) { + authParams = colConcat(authParams, "param(\"" + s.keyParamName + "\")"); } - if(s.isApiKey) { - typedAuthInputParams = csvConcat(typedAuthInputParams, "authParam"+ s.name + ": String"); - authInputParams = csvConcat(authInputParams,"authParam"+ s.name); + if (s.isApiKey) { + typedAuthInputParams = csvConcat(typedAuthInputParams, "authParam" + s.name + ": String"); + authInputParams = csvConcat(authInputParams, "authParam" + s.name); } } } @@ -343,7 +351,6 @@ private void authParameters(CodegenOperation op) { op.vendorExtensions.put("x-codegen-authParams", authParams); op.vendorExtensions.put("x-codegen-authInputParams", authInputParams); op.vendorExtensions.put("x-codegen-typedAuthInputParams", typedAuthInputParams); - } private void generateScalaPath(CodegenOperation op) { @@ -358,7 +365,7 @@ private void generateScalaPath(CodegenOperation op) { // remove last / if (path.endsWith("/")) { - path = path.substring(0, path.length()-1); + path = path.substring(0, path.length() - 1); } String[] items = path.split("/", -1); @@ -387,12 +394,12 @@ private void generateScalaPath(CodegenOperation op) { private void concatParameters(CodegenOperation op) { - String path = colConcat(colConcat(op.vendorExtensions.get("x-codegen-path").toString(),op.vendorExtensions.get("x-codegen-pathParams").toString()), op.vendorExtensions.get("x-codegen-authParams").toString()); + String path = colConcat(colConcat(op.vendorExtensions.get("x-codegen-path").toString(), op.vendorExtensions.get("x-codegen-pathParams").toString()), op.vendorExtensions.get("x-codegen-authParams").toString()); String parameters = csvConcat(op.vendorExtensions.get("x-codegen-inputParams").toString(), op.vendorExtensions.get("x-codegen-authInputParams").toString()); String typedParameters = csvConcat(op.vendorExtensions.get("x-codegen-typedInputParams").toString(), op.vendorExtensions.get("x-codegen-typedAuthInputParams").toString()); // The input parameters for functions - op.vendorExtensions.put("x-codegen-paths",path); + op.vendorExtensions.put("x-codegen-paths", path); op.vendorExtensions.put("x-codegen-params", parameters); op.vendorExtensions.put("x-codegen-typedParams", typedParameters); @@ -409,33 +416,33 @@ private void generateInputParameters(CodegenOperation op) { // TODO: This hacky, should be converted to mappings if possible to keep it clean. // This could also be done using template imports - if(p.isBodyParam) { - p.vendorExtensions.put("x-codegen-normalized-path-type", "jsonBody["+ p.dataType + "]"); + if (p.isBodyParam) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "jsonBody[" + p.dataType + "]"); p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); - } else if(p.isContainer || p.isListContainer) { - p.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(p,"params", false)); + } else if (p.isContainer || p.isListContainer) { + p.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(p, "params", false)); p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType.replaceAll("^[^\\[]+", "Seq")); - } else if(p.isQueryParam) { - p.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(p, "param",true)); + } else if (p.isQueryParam) { + p.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(p, "param", true)); p.vendorExtensions.put("x-codegen-normalized-input-type", toInputParameter(p)); - } else if(p.isHeaderParam) { - p.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(p,"header", true)); + } else if (p.isHeaderParam) { + p.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(p, "header", true)); p.vendorExtensions.put("x-codegen-normalized-input-type", toInputParameter(p)); - } else if(p.isFile) { - p.vendorExtensions.put("x-codegen-normalized-path-type", "fileUpload(\""+ p.paramName + "\")"); + } else if (p.isFile) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "fileUpload(\"" + p.paramName + "\")"); p.vendorExtensions.put("x-codegen-normalized-input-type", "FileUpload"); - } else if(p.isPrimitiveType && !p.isPathParam) { + } else if (p.isPrimitiveType && !p.isPathParam) { p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType.toLowerCase()); p.vendorExtensions.put("x-codegen-normalized-input-type", toInputParameter(p)); } else { //Path paremeters are handled in generateScalaPath() p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); } - if(p.vendorExtensions.get("x-codegen-normalized-path-type") != null){ - pathParams = colConcat(pathParams , p.vendorExtensions.get("x-codegen-normalized-path-type").toString()); + if (p.vendorExtensions.get("x-codegen-normalized-path-type") != null) { + pathParams = colConcat(pathParams, p.vendorExtensions.get("x-codegen-normalized-path-type").toString()); } inputParams = csvConcat(inputParams, p.paramName); - typedInputParams = csvConcat(typedInputParams , p.paramName + ": " + p.vendorExtensions.get("x-codegen-normalized-input-type")); + typedInputParams = csvConcat(typedInputParams, p.paramName + ": " + p.vendorExtensions.get("x-codegen-normalized-input-type")); } 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 old mode 100755 new mode 100644 index ffd425006128..689ae0c1341d --- 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 @@ -1,41 +1,35 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; -import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.*; +import org.openapitools.codegen.utils.ModelUtils; +import org.openapitools.codegen.mustache.*; + +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import org.apache.commons.lang3.StringUtils; + public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String packageName = "io.swagger"; + protected String packageName = "org.openapitools"; protected String packageVersion; - protected String invokerPackage = "io.swagger"; + protected String invokerPackage = "org.openapitools"; protected String sourceFolder = "flash"; public FlashClientCodegen() { super(); - modelPackage = "io.swagger.client.model"; - apiPackage = "io.swagger.client.api"; + modelPackage = "org.openapitools.client.model"; + apiPackage = "org.openapitools.client.api"; outputFolder = "generated-code" + File.separatorChar + "flash"; modelTemplateFiles.put("model.mustache", ".as"); modelTemplateFiles.put("modelList.mustache", "List.as"); @@ -79,7 +73,7 @@ public FlashClientCodegen() { cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "flash package name (convention:" + - " package.name)").defaultValue("io.swagger")); + " package.name)").defaultValue("org.openapitools")); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "flash package version") .defaultValue("1.0.0")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); @@ -107,15 +101,13 @@ public void processOpts() { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); apiPackage = packageName + ".client.api"; modelPackage = packageName + ".client.model"; - } - else { - setPackageName("io.swagger"); + } else { + setPackageName("org.openapitools"); } if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); - } - else { + } else { setPackageVersion("1.0.0"); } @@ -174,12 +166,12 @@ public String getName() { @Override public String getHelp() { - return "Generates a Flash client library."; + return "Generates a Flash (ActionScript) client library (beta)."; } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -198,66 +190,52 @@ public String modelFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty || p instanceof MapProperty) { - return getSwaggerType(p); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p) || ModelUtils.isMapSchema(p)) { + return getSchemaType(p); } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); if (languageSpecificPrimitives.contains(type)) { return type; } } else { - type = toModelName(swaggerType); + type = toModelName(schemaType); } return type; } @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "null"; - } else if (p instanceof BooleanProperty) { + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { return "false"; - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { return "null"; - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { return "null"; - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "0.0"; - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } return "0.0"; - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } return "0"; - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "0"; - } else if (p instanceof MapProperty) { + } else if (ModelUtils.isMapSchema(p)) { return "new Dictionary()"; - } else if (p instanceof ArrayProperty) { + } else if (ModelUtils.isArraySchema(p)) { return "new Array()"; + } else if (ModelUtils.isStringSchema(p)) { + return "null"; } else { return "NaN"; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java index ed436a217e0f..b9dce94919a6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java @@ -1,10 +1,9 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.parameters.Parameter; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import java.io.File; import java.util.*; @@ -33,18 +32,21 @@ public GoClientCodegen() { embeddedTemplateDir = templateDir = "go"; + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + setReservedWordsLowerCase( - Arrays.asList( - // data type - "string", "bool", "uint", "uint8", "uint16", "uint32", "uint64", - "int", "int8", "int16", "int32", "int64", "float32", "float64", - "complex64", "complex128", "rune", "byte", "uintptr", - - "break", "default", "func", "interface", "select", - "case", "defer", "go", "map", "struct", - "chan", "else", "goto", "package", "switch", - "const", "fallthrough", "if", "range", "type", - "continue", "for", "import", "return", "var", "error", "ApiResponse", "nil") + Arrays.asList( + // data type + "string", "bool", "uint", "uint8", "uint16", "uint32", "uint64", + "int", "int8", "int16", "int32", "int64", "float32", "float64", + "complex64", "complex128", "rune", "byte", "uintptr", + + "break", "default", "func", "interface", "select", + "case", "defer", "go", "map", "struct", + "chan", "else", "goto", "package", "switch", + "const", "fallthrough", "if", "range", "type", + "continue", "for", "import", "return", "var", "error", "ApiResponse", "nil") // Added "error" as it's used so frequently that it may as well be a keyword ); @@ -52,31 +54,27 @@ public GoClientCodegen() { .defaultValue("1.0.0")); cliOptions.add(CliOption.newBoolean(WITH_XML, "whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)")); + // option to change the order of form/body parameter + cliOptions.add(CliOption.newBoolean( + CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, + CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS_DESC) + .defaultValue(Boolean.FALSE.toString())); + } @Override public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - } - else { + } else { setPackageName("swagger"); } if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); - } - else { + } else { setPackageVersion("1.0.0"); } @@ -89,7 +87,7 @@ public void processOpts() { modelPackage = packageName; apiPackage = packageName; - supportingFiles.add(new SupportingFile("swagger.mustache", "api", "swagger.yaml")); + supportingFiles.add(new SupportingFile("swagger.mustache", "api", "openapi.yaml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); @@ -98,9 +96,9 @@ public void processOpts() { supportingFiles.add(new SupportingFile("response.mustache", "", "response.go")); supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml")); - if(additionalProperties.containsKey(WITH_XML)) { + if (additionalProperties.containsKey(WITH_XML)) { setWithXml(Boolean.parseBoolean(additionalProperties.get(WITH_XML).toString())); - if ( withXml ) { + if (withXml) { additionalProperties.put(WITH_XML, "true"); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java index 586db2eebf77..bd6bf72621cb 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java @@ -1,10 +1,9 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.parameters.Parameter; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import java.io.File; import java.util.*; @@ -56,17 +55,17 @@ public GoServerCodegen() { * Reserved words. Override this with reserved words specific to your language */ setReservedWordsLowerCase( - Arrays.asList( - // data type - "string", "bool", "uint", "uint8", "uint16", "uint32", "uint64", - "int", "int8", "int16", "int32", "int64", "float32", "float64", - "complex64", "complex128", "rune", "byte", "uintptr", - - "break", "default", "func", "interface", "select", - "case", "defer", "go", "map", "struct", - "chan", "else", "goto", "package", "switch", - "const", "fallthrough", "if", "range", "type", - "continue", "for", "import", "return", "var", "error", "nil") + Arrays.asList( + // data type + "string", "bool", "uint", "uint8", "uint16", "uint32", "uint64", + "int", "int8", "int16", "int32", "int64", "float32", "float64", + "complex64", "complex128", "rune", "byte", "uintptr", + + "break", "default", "func", "interface", "select", + "case", "defer", "go", "map", "struct", + "chan", "else", "goto", "package", "switch", + "const", "fallthrough", "if", "range", "type", + "continue", "for", "import", "return", "var", "error", "nil") // Added "error" as it's used so frequently that it may as well be a keyword ); } @@ -77,8 +76,7 @@ public void processOpts() { if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - } - else { + } else { setPackageName("swagger"); } @@ -99,7 +97,7 @@ public void processOpts() { * entire object tree available. If the input file has a suffix of `.mustache * it will be processed by the template engine. Otherwise, it will be copied */ - supportingFiles.add(new SupportingFile("swagger.mustache", "api", "swagger.yaml")); + supportingFiles.add(new SupportingFile("swagger.mustache", "api", "openapi.yaml")); supportingFiles.add(new SupportingFile("main.mustache", "", "main.go")); supportingFiles.add(new SupportingFile("routers.mustache", apiPath, "routers.go")); supportingFiles.add(new SupportingFile("logger.mustache", apiPath, "logger.go")); 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 a5abafe16bcc..4aad686a9bf4 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 @@ -28,7 +28,7 @@ public GroovyClientCodegen() { //TODO: add doc templates modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); - + apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; configPackage = "io.swagger.configuration"; 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 d20a4167abd5..65f2de3973ca 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 @@ -1,23 +1,17 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.*; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.models.properties.*; - import java.util.*; import java.util.regex.Pattern; import java.io.File; -import io.swagger.models.auth.SecuritySchemeDefinition; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.SupportingFile; -import io.swagger.util.Yaml; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.core.util.Yaml; + import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.lang3.StringUtils; @@ -96,31 +90,31 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC static final String X_STRICT_FIELDS = "x-strictFields"; static final String X_UNKNOWN_MIME_TYPES = "x-unknownMimeTypes"; static final String X_USE_MONAD_LOGGER = "x-useMonadLogger"; - static final String X_ALLOW_NONUNIQUE_OPERATION_IDS = "x-allowNonUniqueOperationIds"; + static final String X_ALLOW_NONUNIQUE_OPERATION_IDS = "x-allowNonUniqueOperationIds"; static final String X_NEWTYPE = "x-newtype"; static final String X_ENUM = "x-enum"; - - protected ArrayList> unknownMimeTypes = new ArrayList<>(); - protected Map> uniqueParamNameTypes = new HashMap<>(); + protected ArrayList> unknownMimeTypes = new ArrayList<>(); + protected Map> uniqueParamNameTypes = new HashMap<>(); protected Map> modelMimeTypes = new HashMap<>(); protected Map knownMimeDataTypes = new HashMap<>(); protected Set typeNames = new HashSet(); protected Set modelTypeNames = new HashSet(); + final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application/.*json(;.*)?"); + public CodegenType getTag() { return CodegenType.CLIENT; } + public String getName() { return "haskell-http-client"; } + public String getHelp() { return "Generates a Haskell http-client library."; } - - final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application/.*json(;.*)?"); - public HaskellHttpClientCodegen() { super(); @@ -142,6 +136,9 @@ public HaskellHttpClientCodegen() { apiPackage = "API"; //modelPackage = "Model"; + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + // Haskell keywords and reserved function names, taken mostly from https://wiki.haskell.org/Keywords setReservedWordsLowerCase( Arrays.asList( @@ -246,7 +243,7 @@ public HaskellHttpClientCodegen() { cliOptions.add(CliOption.newString(PROP_DATETIME_FORMAT, "format string used to parse/render a datetime")); cliOptions.add(CliOption.newString(PROP_DATE_FORMAT, "format string used to parse/render a date").defaultValue(defaultDateFormat)); - cliOptions.add(CliOption.newBoolean(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated").defaultValue(Boolean.TRUE.toString())); + cliOptions.add(CliOption.newBoolean(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC).defaultValue(Boolean.TRUE.toString())); } @@ -254,6 +251,7 @@ public void setAllowNonUniqueOperationIds(Boolean value) { additionalProperties.put(X_ALLOW_NONUNIQUE_OPERATION_IDS, value); this.allowNonUniqueOperationIds = value; } + public void setAllowFromJsonNulls(Boolean value) { additionalProperties.put(PROP_ALLOW_FROMJSON_NULLS, value); } @@ -265,13 +263,16 @@ public void setAllowToJsonNulls(Boolean value) { public void setGenerateModelConstructors(Boolean value) { additionalProperties.put(PROP_GENERATE_MODEL_CONSTRUCTORS, value); } + public void setGenerateEnums(Boolean value) { additionalProperties.put(PROP_GENERATE_ENUMS, value); genEnums = value; } + public void setGenerateFormUrlEncodedInstances(Boolean value) { additionalProperties.put(PROP_GENERATE_FORM_URLENCODED_INSTANCES, value); } + public void setInlineMimeTypes(Boolean value) { additionalProperties.put(PROP_INLINE_MIME_TYPES, value); } @@ -334,18 +335,12 @@ private void setStringProp(String key, String value) { } private String getStringProp(String key) { - return (String)additionalProperties.get(key); + return (String) additionalProperties.get(key); } @Override public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - convertPropertyToBooleanAndWriteBack(CodegenConstants.HIDE_GENERATION_TIMESTAMP); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, true); - } if (additionalProperties.containsKey(PROP_ALLOW_FROMJSON_NULLS)) { setAllowFromJsonNulls(convertPropertyToBoolean(PROP_ALLOW_FROMJSON_NULLS)); @@ -444,11 +439,11 @@ public void processOpts() { } @Override - public void preprocessSwagger(Swagger swagger) { - String baseTitle = swagger.getInfo().getTitle(); + public void preprocessOpenAPI(OpenAPI openAPI) { + String baseTitle = openAPI.getInfo().getTitle(); if (baseTitle == null) { - baseTitle = "Swagger"; + baseTitle = "OpenAPI"; } else { baseTitle = baseTitle.trim(); // Drop any API suffix @@ -488,14 +483,14 @@ public void preprocessSwagger(Swagger swagger) { // root supportingFiles.add(new SupportingFile("haskell-http-client.cabal.mustache", "", getStringProp(PROP_CABAL_PACKAGE) + ".cabal")); - supportingFiles.add(new SupportingFile("swagger.mustache", "", "swagger.yaml")); + supportingFiles.add(new SupportingFile("openapi.mustache", "", "openapi.yaml")); // lib supportingFiles.add(new SupportingFile("TopLevel.mustache", topLevelPath, lastPath + ".hs")); supportingFiles.add(new SupportingFile("Client.mustache", modulePath, "Client.hs")); - if(!allowNonUniqueOperationIds) { + if (!allowNonUniqueOperationIds) { supportingFiles.add(new SupportingFile("APIS.mustache", modulePath, "API.hs")); } supportingFiles.add(new SupportingFile("Core.mustache", modulePath, "Core.hs")); @@ -509,75 +504,65 @@ public void preprocessSwagger(Swagger swagger) { // modelTemplateFiles.put("Model.mustache", ".hs"); // lens - if ((boolean)additionalProperties.get(PROP_GENERATE_LENSES)) { + if ((boolean) additionalProperties.get(PROP_GENERATE_LENSES)) { supportingFiles.add(new SupportingFile("ModelLens.mustache", modulePath, "ModelLens.hs")); } additionalProperties.put("cabalName", getStringProp(PROP_CABAL_PACKAGE)); - additionalProperties.put("pathsName", getStringProp(PROP_CABAL_PACKAGE).replace('-','_')); + additionalProperties.put("pathsName", getStringProp(PROP_CABAL_PACKAGE).replace('-', '_')); additionalProperties.put("requestType", getStringProp(PROP_REQUEST_TYPE)); additionalProperties.put("configType", getStringProp(PROP_CONFIG_TYPE)); - additionalProperties.put("swaggerVersion", swagger.getSwagger()); + additionalProperties.put("openApiVersion", openAPI.getOpenapi()); - super.preprocessSwagger(swagger); + super.preprocessOpenAPI(openAPI); } @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { - try { - objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } + generateYAMLSpecFile(objs); return super.postProcessSupportingFileData(objs); } - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return "(Map.Map String " + getTypeDeclaration(inner) + ")"; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); - if (typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); - } else if (swaggerType == "object") { + if (typeMapping.containsKey(openAPIType)) { + return typeMapping.get(openAPIType); + } else if (openAPIType == "object") { return "A.Value"; } else { - return toModelName(swaggerType); + return toModelName(openAPIType); } } @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - Property additionalProperties2 = ap.getAdditionalProperties(); + public String toInstantiationType(Schema p) { + if (ModelUtils.isMapSchema(p)) { + Schema additionalProperties2 = (Schema) p.getAdditionalProperties(); String type = additionalProperties2.getType(); if (null == type) { - LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" // - + "\tIn Property: " + p); + LOGGER.error("No Type defined for Additional Schema " + additionalProperties2 + "\n" // + + "\tIn Schema: " + p); } - String inner = getSwaggerType(additionalProperties2); + String inner = getSchemaType(additionalProperties2); return "(Map.Map Text " + inner + ")"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); return inner; } else { return null; @@ -636,7 +621,7 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera if (!StringUtils.isBlank(param.collectionFormat)) { param.vendorExtensions.put(X_COLLECTION_FORMAT, mapCollectionFormat(param.collectionFormat)); } - if(!param.required) { + if (!param.required) { op.vendorExtensions.put(X_HAS_OPTIONAL_PARAMS, true); } @@ -664,14 +649,14 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera } @Override - public List fromSecurity(Map schemes) { + public List fromSecurity(Map schemes) { List secs = super.fromSecurity(schemes); - for(CodegenSecurity sec : secs) { - String prefix = ""; - if(sec.isBasic) prefix = "AuthBasic"; - if(sec.isApiKey) prefix = "AuthApiKey"; - if(sec.isOAuth) prefix = "AuthOAuth"; - sec.name = prefix + toTypeName("",sec.name); + for (CodegenSecurity sec : secs) { + String prefix = ""; + if (sec.isBasic) prefix = "AuthBasic"; + if (sec.isApiKey) prefix = "AuthApiKey"; + if (sec.isOAuth) prefix = "AuthOAuth"; + sec.name = prefix + toTypeName("", sec.name); } return secs; } @@ -680,9 +665,9 @@ public List fromSecurity(Map public Map postProcessOperations(Map objs) { Map ret = super.postProcessOperations(objs); - HashMap pathOps = (HashMap)ret.get("operations"); - ArrayList ops = (ArrayList)pathOps.get("operation"); - if(ops.size() > 0) { + HashMap pathOps = (HashMap) ret.get("operations"); + ArrayList ops = (ArrayList) pathOps.get("operation"); + if (ops.size() > 0) { ops.get(0).vendorExtensions.put(X_HAS_NEW_TAG, true); } @@ -707,10 +692,10 @@ public int compare(Map o1, Map o2) { }); additionalProperties.put(X_UNKNOWN_MIME_TYPES, unknownMimeTypes); - ArrayList> params = new ArrayList<>(uniqueParamNameTypes.values()); - Collections.sort(params, new Comparator>() { + ArrayList> params = new ArrayList<>(uniqueParamNameTypes.values()); + Collections.sort(params, new Comparator>() { @Override - public int compare(Map o1, Map o2) { + public int compare(Map o1, Map o2) { return ((String) o1.get(X_PARAM_NAME_TYPE)) .compareTo( @@ -728,7 +713,7 @@ public Map postProcessOperationsWithModels(Map o if (modelMimeTypes.containsKey(m.classname)) { Set mimeTypes = modelMimeTypes.get(m.classname); m.vendorExtensions.put(X_MIME_TYPES, mimeTypes); - if ((boolean)additionalProperties.get(PROP_GENERATE_FORM_URLENCODED_INSTANCES) && mimeTypes.contains("MimeFormUrlEncoded")) { + if ((boolean) additionalProperties.get(PROP_GENERATE_FORM_URLENCODED_INSTANCES) && mimeTypes.contains("MimeFormUrlEncoded")) { Boolean hasMimeFormUrlEncoded = true; for (CodegenProperty v : m.vars) { if (!(v.isPrimitiveType || v.isString || v.isDate || v.isDateTime)) { @@ -746,7 +731,7 @@ public Map postProcessOperationsWithModels(Map o } @Override - public CodegenModel fromModel(String name, Model mod, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema mod, Map allDefinitions) { CodegenModel model = super.fromModel(name, mod, allDefinitions); while (typeNames.contains(model.classname)) { @@ -796,12 +781,12 @@ public boolean isDataTypeBinary(final String dataType) { private void processReturnType(CodegenOperation op) { String returnType = op.returnType; if (returnType == null || returnType.equals("null")) { - if(op.hasProduces) { + if (op.hasProduces) { returnType = "res"; op.vendorExtensions.put(X_HAS_UNKNOWN_RETURN, true); } else { returnType = "NoContent"; - if(!op.vendorExtensions.containsKey(X_INLINE_ACCEPT)) { + if (!op.vendorExtensions.containsKey(X_INLINE_ACCEPT)) { SetNoContent(op, X_INLINE_ACCEPT); } } @@ -917,7 +902,7 @@ private void addToUniques(String xGroup, String paramNameType, String dataType, private void addEnumToUniques(String paramNameType, String datatype, String enumValues, Map allowableValues, String description) { HashMap props = new HashMap<>(); props.put("allowableValues", allowableValues); - if(StringUtils.isNotBlank(description)) { + if (StringUtils.isNotBlank(description)) { props.put("description", description); } props.put(X_ENUM_VALUES, enumValues); @@ -970,9 +955,9 @@ private void processMediaType(CodegenOperation op, Map m) { } private Boolean unknownMimeTypesContainsType(String mimeType) { - for(Map m : unknownMimeTypes) { + for (Map m : unknownMimeTypes) { String mimeType0 = m.get(X_MEDIA_DATA_TYPE); - if(mimeType0 != null && mimeType0.equals(mimeType)) { + if (mimeType0 != null && mimeType0.equals(mimeType)) { return true; } } @@ -1024,7 +1009,7 @@ private String getMimeDataType(String mimeType) { if (knownMimeDataTypes.containsKey(mimeType)) { return knownMimeDataTypes.get(mimeType); } - String shortenedName = mimeType.replaceFirst("application/",""); + String shortenedName = mimeType.replaceFirst("application/", ""); return "Mime" + toTypeName("", shortenedName); } @@ -1039,8 +1024,9 @@ private static String generateNextName(String name) { return name + "2"; } } + private static boolean isMultipartOperation(List> consumes) { - for(Map consume : consumes) { + for (Map consume : consumes) { if (consume != null) { if ("multipart/form-data".equals(consume.get(MEDIA_TYPE))) { return true; @@ -1054,11 +1040,12 @@ private static boolean isMultipartOperation(List> consumes) public String toVarName(String name) { return toVarName("", name); } + public String toVarName(String prefix, String name) { Boolean hasPrefix = !StringUtils.isBlank(prefix); name = underscore(sanitizeName(name.replaceAll("-", "_"))); name = camelize(name, !hasPrefix); - if(hasPrefix) { + if (hasPrefix) { return prefix + name; } else { if (name.matches("^\\d.*")) @@ -1078,38 +1065,45 @@ public String toParamName(String name) { public String toModelName(String name) { return toTypeName("Model", name); } + @Override public String toModelFilename(String name) { return toTypeName("Model", name); } + public String toApiName(String name) { if (name.length() == 0) { return "Default"; } return toTypeName("Api", name); } + @Override public String toApiFilename(String name) { return toTypeName("Api", name); } + @Override public String apiFileFolder() { return outputFolder + File.separator + this.modulePath + File.separator + "API"; } + public String toTypeName(String prefix, String name) { - name = escapeIdentifier(prefix, camelize(sanitizeName(name))); + name = escapeIdentifier(prefix, camelize(sanitizeName(name))); return name; } + @Override public String toOperationId(String operationId) { if (StringUtils.isEmpty(operationId)) { throw new RuntimeException("Empty method/operation name (operationId) not allowed"); } - operationId = escapeIdentifier("op",camelize(sanitizeName(operationId), true)); + operationId = escapeIdentifier("op", camelize(sanitizeName(operationId), true)); return operationId; } + public String escapeIdentifier(String prefix, String name) { - if(StringUtils.isBlank(prefix)) return name; + if (StringUtils.isBlank(prefix)) return name; if (isReservedWord(name)) { name = prefix + name; @@ -1125,6 +1119,7 @@ public String escapeIdentifier(String prefix, String name) { } return name; } + static boolean isJsonMimeType(String mime) { return mime != null && JSON_MIME_PATTERN.matcher(mime).matches(); } @@ -1134,16 +1129,14 @@ static boolean isWildcardMimeType(String mime) { } @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - return "\"" + escapeText(dp.getDefault()) + "\""; + public String toDefaultValue(Schema p) { + if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return "\"" + escapeText((String) p.getDefault()) + "\""; } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getDefault() != null) { - if (dp.getDefault().toString().equalsIgnoreCase("false")) + } else if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + if (p.getDefault().toString().equalsIgnoreCase("false")) return "False"; else return "True"; @@ -1160,7 +1153,7 @@ public Map postProcessModels(Map objs) { Map mo = (Map) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); cm.isEnum = genEnums && cm.isEnum; - if(cm.isAlias) { + if (cm.isAlias) { cm.vendorExtensions.put(X_DATA_TYPE, cm.dataType); } for (CodegenProperty var : cm.vars) { @@ -1243,7 +1236,7 @@ public void updateCodegenPropertyEnumValues(CodegenProperty var, String paramNam updateCodegenPropertyEnumValues(var.items, var.items.datatypeWithEnum); return; } - if(var.isEnum && var.allowableValues != null) { + if (var.isEnum && var.allowableValues != null) { updateAllowableValuesNames(paramNameType, var.allowableValues); } } @@ -1261,7 +1254,7 @@ private void updateAllowableValuesNames(String paramNameType, Map num = new ArrayList<>(Arrays.asList("integer","int","double","long","float")); + List num = new ArrayList<>(Arrays.asList("integer", "int", "double", "long", "float")); if (value.length() == 0) { return "'Empty"; } @@ -1285,8 +1278,8 @@ public String toEnumVarName(String value, String datatype) { @Override public String toEnumValue(String value, String datatype) { - List num = new ArrayList<>(Arrays.asList("integer","int","double","long","float")); - if(num.contains(datatype.toLowerCase())) { + List num = new ArrayList<>(Arrays.asList("integer", "int", "double", "long", "float")); + if (num.contains(datatype.toLowerCase())) { return value; } else { return "\"" + escapeText(value) + "\""; @@ -1309,7 +1302,7 @@ public String escapeText(String input) { StringEscapeUtils.unescapeJava( StringEscapeUtils.escapeJava(input) .replace("\\/", "/")) - .replaceAll("[\\t\\n\\r]"," ") + .replaceAll("[\\t\\n\\r]", " ") .replace("\\", "\\\\") .replace("\"", "\\\"")); } 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 815e118ec0c0..494e3cc7af62 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 @@ -1,12 +1,22 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.*; -import io.swagger.models.ModelImpl; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.*; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.media.*; import java.util.*; import java.util.regex.Pattern; @@ -22,7 +32,6 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf * Configures the type of generator. * * @return the CodegenType for this generator - * @see org.openapitools.codegen.CodegenType */ public CodegenType getTag() { return CodegenType.SERVER; @@ -136,7 +145,7 @@ public HaskellServantCodegen() { typeMapping.put("set", "Set"); typeMapping.put("boolean", "Bool"); typeMapping.put("string", "Text"); - typeMapping.put("int", "Int"); + typeMapping.put("integer", "Int"); typeMapping.put("long", "Integer"); typeMapping.put("short", "Int"); typeMapping.put("char", "Char"); @@ -145,10 +154,10 @@ public HaskellServantCodegen() { typeMapping.put("DateTime", "Integer"); typeMapping.put("file", "FilePath"); typeMapping.put("number", "Double"); - typeMapping.put("integer", "Int"); typeMapping.put("any", "Value"); typeMapping.put("UUID", "Text"); typeMapping.put("ByteArray", "Text"); + typeMapping.put("object", "Value"); importMapping.clear(); importMapping.put("Map", "qualified Data.Map as Map"); @@ -192,13 +201,13 @@ public String firstLetterToLower(String word) { } @Override - public void preprocessSwagger(Swagger swagger) { + public void preprocessOpenAPI(OpenAPI openAPI) { // From the title, compute a reasonable name for the package and the API - String title = swagger.getInfo().getTitle(); + String title = openAPI.getInfo().getTitle(); // Drop any API suffix if(title == null) { - title = "Swagger"; + title = "OpenAPI"; } else { title = title.trim(); if (title.toUpperCase().endsWith("API")) { @@ -233,7 +242,7 @@ public void preprocessSwagger(Swagger swagger) { additionalProperties.put("package", cabalName); // Due to the way servant resolves types, we need a high context stack limit - additionalProperties.put("contextStackLimit", swagger.getPaths().size() * 2 + 300); + additionalProperties.put("contextStackLimit", openAPI.getPaths().size() * 2 + 300); List> replacements = new ArrayList<>(); Object[] replacementChars = specialCharReplacements.keySet().toArray(); @@ -247,7 +256,7 @@ public void preprocessSwagger(Swagger swagger) { } additionalProperties.put("specialCharReplacements", replacements); - super.preprocessSwagger(swagger); + super.preprocessOpenAPI(openAPI); } @@ -258,59 +267,58 @@ public void preprocessSwagger(Swagger swagger) { * @return a string value used as the `dataType` field for model templates, `returnType` for api templates */ @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return "Map.Map String " + getTypeDeclaration(inner); } return fixModelChars(super.getTypeDeclaration(p)); } /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * Optional - OpenAPI type conversion. This is used to map OpenAPI types in a `Schema` into * either language specific types via `typeMapping` or into complex models if there is not a mapping. * * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property */ @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); + LOGGER.debug("debugging swager type: " + p.getType() + ", " + p.getFormat() + " => " + schemaType); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) - return toModelName(type); - } else if(swaggerType == "object") { - type = "Value"; - } else if(typeMapping.containsValue(swaggerType)) { - type = swaggerType + "_"; + if (typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); + return type; + //if (languageSpecificPrimitives.contains(type)) + // return toModelName(type); + } else if(typeMapping.containsValue(schemaType)) { + // TODO what's this case for? + type = schemaType + "_"; } else { - type = swaggerType; + type = schemaType; } + // it's a model return toModelName(type); } @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - Property additionalProperties2 = ap.getAdditionalProperties(); + public String toInstantiationType(Schema p) { + if (ModelUtils.isMapSchema(p)) { + Schema additionalProperties2 = (Schema) p.getAdditionalProperties(); String type = additionalProperties2.getType(); if (null == type) { LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" // + "\tIn Property: " + p); } - String inner = getSwaggerType(additionalProperties2); + String inner = getSchemaType(additionalProperties2); return "(Map.Map Text " + inner + ")"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); // Return only the inner type; the wrapping with QueryList is done // somewhere else, where we have access to the collection format. return inner; @@ -390,8 +398,8 @@ private List pathToClientType(String path, List pathPa @Override - public CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(resourcePath, httpMethod, operation, definitions, swagger); + public CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions, OpenAPI openAPI) { + CodegenOperation op = super.fromOperation(resourcePath, httpMethod, operation, definitions, openAPI); List path = pathToServantRoute(op.path, op.pathParams); List type = pathToClientType(op.path, op.pathParams); @@ -400,6 +408,9 @@ public CodegenOperation fromOperation(String resourcePath, String httpMethod, Op for (CodegenParameter param : op.queryParams) { String paramType = param.dataType; if (param.isListContainer) { + if (StringUtils.isEmpty(param.collectionFormat)) { + param.collectionFormat = "csv"; + } paramType = makeQueryListType(paramType, param.collectionFormat); } path.add("QueryParam \"" + param.baseName + "\" " + paramType); @@ -421,7 +432,8 @@ public CodegenOperation fromOperation(String resourcePath, String httpMethod, Op bodyType = formName; path.add("ReqBody '[FormUrlEncoded] " + formName); } - if(bodyType != null) { + + if (bodyType != null) { type.add(bodyType); } @@ -431,11 +443,19 @@ public CodegenOperation fromOperation(String resourcePath, String httpMethod, Op String paramType = param.dataType; if (param.isListContainer) { + if (StringUtils.isEmpty(param.collectionFormat)) { + param.collectionFormat = "csv"; + } paramType = makeQueryListType(paramType, param.collectionFormat); } type.add("Maybe " + paramType); } + // store form parameter name in the vendor extensions + for (CodegenParameter param : op.formParams) { + param.vendorExtensions.put("x-formParamName", camelize(param.baseName)); + } + // Add the HTTP method and return type String returnType = op.returnType; if (returnType == null || returnType.equals("null")) { @@ -499,7 +519,7 @@ private String fixModelChars(String string) { // Override fromModel to create the appropriate model namings @Override - public CodegenModel fromModel(String name, Model mod, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema mod, Map allDefinitions) { CodegenModel model = super.fromModel(name, mod, allDefinitions); // Clean up the class name to remove invalid characters @@ -516,14 +536,8 @@ public CodegenModel fromModel(String name, Model mod, Map allDefi // Create newtypes for things with non-object types String dataOrNewtype = "data"; - // check if it's a ModelImpl before casting - if (!(mod instanceof ModelImpl)) { - return model; - } - - String modelType = ((ModelImpl) mod).getType(); - if(modelType != "object" && typeMapping.containsKey(modelType)) { - String newtype = typeMapping.get(modelType); + if(model.dataType != "object" && typeMapping.containsKey(model.dataType)) { + String newtype = typeMapping.get(model.dataType); model.vendorExtensions.put("x-customNewtype", newtype); } @@ -534,14 +548,6 @@ public CodegenModel fromModel(String name, Model mod, Map allDefi return model; } - @Override - public CodegenParameter fromParameter(Parameter param, Set imports) { - CodegenParameter p = super.fromParameter(param, imports); - p.vendorExtensions.put("x-formParamName", camelize(p.baseName)); - p.dataType = fixModelChars(p.dataType); - return p; - } - @Override public String escapeQuotationMark(String input) { // remove " to avoid code injection diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterCodegen.java index 934ec80f6d83..6ca000709feb 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterCodegen.java @@ -1,201 +1,201 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.Swagger; -import io.swagger.models.properties.*; +import org.openapitools.codegen.utils.*; +import org.openapitools.codegen.mustache.*; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.oas.models.info.Info; + import java.util.*; import java.io.File; public class JMeterCodegen extends DefaultCodegen implements CodegenConfig { - // source folder where to write the files - protected String sourceFolder = ""; - protected String apiVersion = "1.0.0"; - - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see org.openapitools.codegen.CodegenType - */ - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. - * - * @return the friendly name for the generator - */ - @Override - public String getName() { - return "jmeter"; - } - - /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here - * - * @return A string value for the help message - */ - @Override - public String getHelp() { - return "Generates a JMeter .jmx file."; - } - - public JMeterCodegen() { - super(); - - // set the output folder here - outputFolder = "generated-code/JMeterCodegen"; - - /* - * Api classes. You can write classes for each Api file with the apiTemplateFiles map. - * as with models, add multiple entries with different extensions for multiple files per - * class - */ - apiTemplateFiles.put( - "api.mustache", // the template to use - ".jmx"); // the extension for each file to write - - apiTemplateFiles.put("testdata-localhost.mustache", ".csv"); + // source folder where to write the files + protected String sourceFolder = ""; + protected String apiVersion = "1.0.0"; - /* - * Template Location. This is the location which templates will be read from. The generator - * will use the resource stream to attempt to read the templates. + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see org.openapitools.codegen.CodegenType */ - embeddedTemplateDir = templateDir = "JMeter"; + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } - /* - * Api Package. Optional, if needed, this can be used in templates + /** + * Configures a friendly name for the generator. This will be used by the generator + * to select the library with the -l flag. + * + * @return the friendly name for the generator */ - apiPackage = ""; + @Override + public String getName() { + return "jmeter"; + } - /* - * Model Package. Optional, if needed, this can be used in templates + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message */ - modelPackage = ""; + @Override + public String getHelp() { + return "Generates a JMeter .jmx file."; + } - /* - * Reserved words. Override this with reserved words specific to your language - */ - reservedWords = new HashSet ( - Arrays.asList( - "sample1", // replace with static values - "sample2") - ); - - /* - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files - */ - additionalProperties.put("apiVersion", apiVersion); - -// supportingFiles.add(new SupportingFile("testdata-localhost.mustache", "input", "testdata-localhost.csv")); - } - - @Override - public void preprocessSwagger(Swagger swagger) { - if (swagger != null && swagger.getPaths() != null) { - for (String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if (path.getOperations() != null) { - for (Operation operation : path.getOperations()) { - String pathWithDollars = pathname.replaceAll("\\{", "\\$\\{"); - operation.setVendorExtension("x-path", pathWithDollars); - } + public JMeterCodegen() { + super(); + + // set the output folder here + outputFolder = "generated-code/JMeterCodegen"; + + /* + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put( + "api.mustache", // the template to use + ".jmx"); // the extension for each file to write + + apiTemplateFiles.put("testdata-localhost.mustache", ".csv"); + + /* + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + embeddedTemplateDir = templateDir = "JMeter"; + + /* + * Api Package. Optional, if needed, this can be used in templates + */ + apiPackage = ""; + + /* + * Model Package. Optional, if needed, this can be used in templates + */ + modelPackage = ""; + + /* + * Reserved words. Override this with reserved words specific to your language + */ + reservedWords = new HashSet( + Arrays.asList( + "sample1", // replace with static values + "sample2") + ); + + /* + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + // supportingFiles.add(new SupportingFile("testdata-localhost.mustache", "input", "testdata-localhost.csv")); + } + + @Override + public void preprocessOpenAPI(OpenAPI openAPI) { + if (openAPI != null && openAPI.getPaths() != null) { + for (String pathname : openAPI.getPaths().keySet()) { + PathItem path = openAPI.getPaths().get(pathname); + if (path.readOperations() != null) { + for (Operation operation : path.readOperations()) { + String pathWithDollars = pathname.replaceAll("\\{", "\\$\\{"); + operation.addExtension("x-path", pathWithDollars); + } + } + } } - } } - } - - /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reserved words - * - * @return the escaped term - */ + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reserved words + * + * @return the escaped term + */ @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; } - /** - * Location to write model files. You can use the modelPackage() as defined when the class is - * instantiated - */ - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - /** - * Location to write api files. You can use the apiPackage() as defined when the class is - * instantiated - */ - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - /** - * Optional - type declaration. This is a String which is used by the templates to instantiate your - * types. There is typically special handling for different property types - * - * @return a string value used as the `dataType` field for model templates, `returnType` for api templates - */ - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + /** + * Location to write model files. You can use the modelPackage() as defined when the class is + * instantiated + */ + @Override + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); } - return super.getTypeDeclaration(p); - } - - /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into - * either language specific types via `typeMapping` or into complex models if there is not a mapping. - * - * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property - */ - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) + + /** + * Optional - type declaration. This is a String which is used by the templates to instantiate your + * types. There is typically special handling for different property types + * + * @return a string value used as the `dataType` field for model templates, `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + /** + * Optional - swagger type conversion. This is used to map swagger types in a `Schema` into + * either language specific types via `typeMapping` or into complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + */ + @Override + public String getSchemaType(Schema p) { + String swaggerType = super.getSchemaType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return toModelName(type); + } else + type = swaggerType; return toModelName(type); } - else - type = swaggerType; - return toModelName(type); - } - - @Override - public String escapeQuotationMark(String input) { - // remove ' to avoid code injection - return input.replace("'", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } + + @Override + public String escapeQuotationMark(String input) { + // remove ' to avoid code injection + return input.replace("'", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java index 527cef3691b6..148e318403f7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java @@ -1,4 +1,3 @@ - package org.openapitools.codegen.languages; import java.io.File; @@ -8,22 +7,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.*; import org.openapitools.codegen.languages.features.BeanValidationFeatures; import org.openapitools.codegen.languages.features.GzipTestFeatures; import org.openapitools.codegen.languages.features.LoggingTestFeatures; import org.openapitools.codegen.languages.features.UseGenericResponseFeatures; -import io.swagger.models.Operation; +import io.swagger.v3.oas.models.*; public class JavaCXFClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures, UseGenericResponseFeatures, GzipTestFeatures, LoggingTestFeatures { -private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFClientCodegen.class); + private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFClientCodegen.class); /** * Name of the sub-directory in "src/main/resource" where to find the @@ -32,15 +26,14 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS"; protected boolean useBeanValidation = false; - + protected boolean useGenericResponse = false; protected boolean useGzipFeatureForTests = false; protected boolean useLoggingFeatureForTests = false; - public JavaCXFClientCodegen() - { + public JavaCXFClientCodegen() { super(); supportsInheritance = true; @@ -78,15 +71,14 @@ public JavaCXFClientCodegen() @Override - public void processOpts() - { + public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(USE_BEANVALIDATION)) { boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION); this.setUseBeanValidation(useBeanValidationProp); } - + if (additionalProperties.containsKey(USE_GENERIC_RESPONSE)) { this.setUseGenericResponse(convertPropertyToBoolean(USE_GENERIC_RESPONSE)); } @@ -106,15 +98,13 @@ public void processOpts() } @Override - public String getName() - { + public String getName() { return "jaxrs-cxf-client"; } @Override - public CodegenType getTag() - { + public CodegenType getTag() { return CodegenType.CLIENT; } @@ -134,30 +124,13 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } @Override - @SuppressWarnings("unchecked") public Map postProcessOperations(Map objs) { objs = super.postProcessOperations(objs); - - Map operations = (Map) objs.get("operations"); - if (operations != null) { - List ops = (List) operations.get("operation"); - for (CodegenOperation operation : ops) { - - if (operation.returnType == null) { - operation.returnType = "void"; - // set vendorExtensions.x-java-is-response-void to true as - // returnType is set to "void" - operation.vendorExtensions.put("x-java-is-response-void", true); - } - } - } - - return operations; + return AbstractJavaJAXRSServerCodegen.jaxrsPostProcessOperations(objs); } @Override - public String getHelp() - { + public String getHelp() { return "Generates a Java JAXRS Client based on Apache CXF framework."; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFServerCodegen.java index ab9127573bb7..6cd4bdbf4973 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFServerCodegen.java @@ -1,4 +1,3 @@ - package org.openapitools.codegen.languages; import java.io.File; @@ -8,40 +7,35 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.*; import org.openapitools.codegen.languages.features.CXFServerFeatures; import org.openapitools.codegen.languages.features.GzipTestFeatures; import org.openapitools.codegen.languages.features.LoggingTestFeatures; import org.openapitools.codegen.languages.features.UseGenericResponseFeatures; -import io.swagger.models.Operation; +import io.swagger.v3.oas.models.*; public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen - implements CXFServerFeatures, GzipTestFeatures, LoggingTestFeatures, UseGenericResponseFeatures -{ + implements CXFServerFeatures, GzipTestFeatures, LoggingTestFeatures, UseGenericResponseFeatures { private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFServerCodegen.class); - + protected boolean addConsumesProducesJson = true; protected boolean generateSpringApplication = false; - + protected boolean useSpringAnnotationConfig = false; protected boolean useSwaggerFeature = false; - + protected boolean useSwaggerUI = false; protected boolean useWadlFeature = false; - + protected boolean useMultipartFeature = false; protected boolean useBeanValidationFeature = false; - - protected boolean generateSpringBootApplication= false; - + + protected boolean generateSpringBootApplication = false; + protected boolean generateJbossDeploymentDescriptor = false; protected boolean useGzipFeature = false; @@ -58,18 +52,17 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen protected boolean useGenericResponse = false; - public JavaCXFServerCodegen() - { + public JavaCXFServerCodegen() { super(); supportsInheritance = true; - + artifactId = "swagger-cxf-server"; - + outputFolder = "generated-code/JavaJaxRS-CXF"; - + apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); - + // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment //TODO: add doc templates @@ -85,7 +78,7 @@ public JavaCXFServerCodegen() cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_APPLICATION, "Generate Spring application")); cliOptions.add(CliOption.newBoolean(USE_SPRING_ANNOTATION_CONFIG, "Use Spring Annotation Config")); - + cliOptions.add(CliOption.newBoolean(USE_SWAGGER_FEATURE, "Use Swagger Feature")); cliOptions.add(CliOption.newBoolean(USE_SWAGGER_UI, "Use Swagger UI")); @@ -98,14 +91,14 @@ public JavaCXFServerCodegen() cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION_FEATURE, "Use BeanValidation Feature")); cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE, "Use Logging Feature")); cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE_FOR_TESTS, "Use Logging Feature for tests")); - + cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_BOOT_APPLICATION, "Generate Spring Boot application")); cliOptions.add( CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, "Generate Jboss Deployment Descriptor")); - + cliOptions .add(CliOption.newBoolean(ADD_CONSUMES_PRODUCES_JSON, "Add @Consumes/@Produces Json to API interface")); - + cliOptions.add(CliOption.newBoolean(USE_ANNOTATED_BASE_PATH, "Use @Path annotations for basePath")); cliOptions.add(CliOption.newBoolean(GENERATE_NON_SPRING_APPLICATION, "Generate non-Spring application")); @@ -115,14 +108,13 @@ public JavaCXFServerCodegen() @Override - public void processOpts() - { + public void processOpts() { super.processOpts(); - + if (additionalProperties.containsKey(ADD_CONSUMES_PRODUCES_JSON)) { this.setAddConsumesProducesJson(convertPropertyToBooleanAndWriteBack(ADD_CONSUMES_PRODUCES_JSON)); } - + if (additionalProperties.containsKey(USE_GENERIC_RESPONSE)) { this.setUseGenericResponse(convertPropertyToBoolean(USE_GENERIC_RESPONSE)); } @@ -133,7 +125,7 @@ public void processOpts() if (additionalProperties.containsKey(GENERATE_SPRING_APPLICATION)) { this.setGenerateSpringApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_APPLICATION)); - + this.setUseSwaggerFeature(convertPropertyToBooleanAndWriteBack(USE_SWAGGER_FEATURE)); this.setUseSwaggerUI(convertPropertyToBooleanAndWriteBack(USE_SWAGGER_UI)); @@ -144,16 +136,16 @@ public void processOpts() this.setUseLoggingFeature(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE)); this.setUseLoggingFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE_FOR_TESTS)); this.setUseSpringAnnotationConfig(convertPropertyToBooleanAndWriteBack(USE_SPRING_ANNOTATION_CONFIG)); - + boolean useBeanValidationFeature = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION_FEATURE); this.setUseBeanValidationFeature(useBeanValidationFeature); if (useBeanValidationFeature) { LOGGER.info("make sure your target server supports Bean Validation 1.1"); } - + this.setGenerateSpringBootApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_BOOT_APPLICATION)); } - + if (additionalProperties.containsKey(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)) { boolean generateJbossDeploymentDescriptorProp = convertPropertyToBooleanAndWriteBack( GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); @@ -171,29 +163,29 @@ public void processOpts() } supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen - + writeOptional(outputFolder, new SupportingFile("server/pom.mustache", "", "pom.xml")); - + writeOptional(outputFolder, new SupportingFile("server/swagger-codegen-ignore.mustache", "", ".swagger-codegen-ignore")); if (this.generateSpringApplication) { writeOptional(outputFolder, new SupportingFile("server/readme.md", "", "readme.md")); - + writeOptional(outputFolder, new SupportingFile("server/ApplicationContext.xml.mustache", ("src/main/resources"), "ApplicationContext.xml")); writeOptional(outputFolder, new SupportingFile("server/web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); writeOptional(outputFolder, new SupportingFile("server/context.xml.mustache", ("src/main/webapp/WEB-INF"), "context.xml")); - + // Jboss if (generateJbossDeploymentDescriptor) { writeOptional(outputFolder, new SupportingFile("server/jboss-web.xml.mustache", ("src/main/webapp/WEB-INF"), "jboss-web.xml")); } - + // Spring Boot if (this.generateSpringBootApplication) { writeOptional(outputFolder, new SupportingFile("server/SpringBootApplication.mustache", @@ -203,25 +195,24 @@ public void processOpts() } } - + if (this.generateNonSpringApplication) { writeOptional(outputFolder, new SupportingFile("server/nonspring-web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); } } - + @Override - public String getName() - { + public String getName() { return "jaxrs-cxf"; } @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - super.addOperationToGroup(tag, resourcePath, operation, co, operations); + super.addOperationToGroup(tag, resourcePath, operation, co, operations); co.subresourceOperation = !co.path.isEmpty(); } - + @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); @@ -230,13 +221,12 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert model.imports.remove("JsonSerialize"); model.imports.remove("ToStringSerializer"); } - + @Override - public String getHelp() - { + public String getHelp() { return "Generates a Java JAXRS Server application based on Apache CXF framework."; } - + public void setGenerateSpringApplication(boolean generateSpringApplication) { this.generateSpringApplication = generateSpringApplication; } @@ -273,7 +263,7 @@ public void setUseLoggingFeature(boolean useLoggingFeature) { public void setUseBeanValidationFeature(boolean useBeanValidationFeature) { this.useBeanValidationFeature = useBeanValidationFeature; } - + public void setGenerateSpringBootApplication(boolean generateSpringBootApplication) { this.generateSpringBootApplication = generateSpringBootApplication; } @@ -305,7 +295,7 @@ public void setUseAnnotatedBasePath(boolean useAnnotatedBasePath) { public void setGenerateNonSpringApplication(boolean generateNonSpringApplication) { this.generateNonSpringApplication = generateNonSpringApplication; } - + public void setUseGenericResponse(boolean useGenericResponse) { this.useGenericResponse = useGenericResponse; } 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 ff62be4e58e8..a632153634ab 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 @@ -3,6 +3,7 @@ import static java.util.Collections.sort; import com.google.common.collect.LinkedListMultimap; + import org.openapitools.codegen.*; import org.openapitools.codegen.languages.features.BeanValidationFeatures; import org.openapitools.codegen.languages.features.GzipFeatures; @@ -19,8 +20,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures, PerformBeanValidationFeatures, - GzipFeatures -{ + GzipFeatures { static final String MEDIA_TYPE = "mediaType"; @SuppressWarnings("hiding") @@ -171,7 +171,7 @@ public void processOpts() { writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); - if(!("resttemplate".equals(getLibrary()) || REST_ASSURED.equals(getLibrary()))) { + if (!("resttemplate".equals(getLibrary()) || REST_ASSURED.equals(getLibrary()))) { supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); } @@ -182,12 +182,12 @@ public void processOpts() { supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); } - supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew") ); - supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") ); - supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache", - gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") ); - supportingFiles.add(new SupportingFile( "gradle-wrapper.jar", - gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") ); + supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); + supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); + supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); + supportingFiles.add(new SupportingFile("gradle-wrapper.jar", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); @@ -197,7 +197,7 @@ public void processOpts() { } //TODO: add doc to retrofit1 and feign - if ( "feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) ){ + if ("feign".equals(getLibrary()) || "retrofit".equals(getLibrary())) { modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); } @@ -233,15 +233,15 @@ public void processOpts() { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); additionalProperties.put("jackson", "true"); - } else if ("resteasy".equals(getLibrary())) { + } else if ("resteasy".equals(getLibrary())) { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); additionalProperties.put("jackson", "true"); - } else if("jersey1".equals(getLibrary())) { + } else if ("jersey1".equals(getLibrary())) { additionalProperties.put("jackson", "true"); - } else if("resttemplate".equals(getLibrary())) { + } else if ("resttemplate".equals(getLibrary())) { additionalProperties.put("jackson", "true"); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); - } else if("vertx".equals(getLibrary())) { + } else if ("vertx".equals(getLibrary())) { typeMapping.put("file", "AsyncFile"); importMapping.put("AsyncFile", "io.vertx.core.file.AsyncFile"); setJava8Mode(true); @@ -253,7 +253,7 @@ public void processOpts() { } else if ("google-api-client".equals(getLibrary())) { additionalProperties.put("jackson", "true"); - } else if (REST_ASSURED.equals(getLibrary())) { + } else if (REST_ASSURED.equals(getLibrary())) { additionalProperties.put("gson", "true"); apiTemplateFiles.put("api.mustache", ".java"); supportingFiles.add(new SupportingFile("ResponseSpecBuilders.mustache", invokerFolder, "ResponseSpecBuilders.java")); @@ -331,12 +331,11 @@ public Map postProcessOperations(Map objs) { if (isMultipartType(operation.consumes)) { operation.isMultipart = Boolean.TRUE; - } - else { + } else { operation.prioritizedContentTypes = prioritizeContentTypes(operation.consumes); } } - if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")){ + if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) { operation.path = operation.path.substring(1); } @@ -348,7 +347,7 @@ public int compare(CodegenParameter one, CodegenParameter another) { if (one.isPathParam && another.isQueryParam) { return -1; } - if (one.isQueryParam && another.isPathParam){ + if (one.isQueryParam && another.isPathParam) { return 1; } @@ -356,7 +355,7 @@ public int compare(CodegenParameter one, CodegenParameter another) { } }); Iterator iterator = operation.allParams.iterator(); - while (iterator.hasNext()){ + while (iterator.hasNext()) { CodegenParameter param = iterator.next(); param.hasMore = iterator.hasNext(); } @@ -377,7 +376,7 @@ public int compare(CodegenParameter one, CodegenParameter another) { 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] = "{" + camelize(items[i].substring(1, items[i].length() - 1), true) + "}"; } } op.path = StringUtils.join(items, "/"); @@ -389,7 +388,7 @@ public int compare(CodegenParameter one, CodegenParameter another) { @Override public String apiFilename(String templateName, String tag) { - if("vertx".equals(getLibrary())) { + if ("vertx".equals(getLibrary())) { String suffix = apiTemplateFiles().get(templateName); String subFolder = ""; if (templateName.startsWith("rx")) { @@ -402,15 +401,15 @@ public String apiFilename(String templateName, String tag) { } /** - * Prioritizes consumes mime-type list by moving json-vendor and json mime-types up front, but - * otherwise preserves original consumes definition order. - * [application/vnd...+json,... application/json, ..as is..] + * Prioritizes consumes mime-type list by moving json-vendor and json mime-types up front, but + * otherwise preserves original consumes definition order. + * [application/vnd...+json,... application/json, ..as is..] * * @param consumes consumes mime-type list * @return */ static List> prioritizeContentTypes(List> consumes) { - if ( consumes.size() <= 1 ) + if (consumes.size() <= 1) return consumes; List> prioritizedContentTypes = new ArrayList<>(consumes.size()); @@ -418,14 +417,12 @@ static List> prioritizeContentTypes(List List> jsonVendorMimeTypes = new ArrayList<>(consumes.size()); List> jsonMimeTypes = new ArrayList<>(consumes.size()); - for ( Map consume : consumes) { - if ( isJsonVendorMimeType(consume.get(MEDIA_TYPE))) { + for (Map consume : consumes) { + if (isJsonVendorMimeType(consume.get(MEDIA_TYPE))) { jsonVendorMimeTypes.add(consume); - } - else if ( isJsonMimeType(consume.get(MEDIA_TYPE))) { + } else if (isJsonMimeType(consume.get(MEDIA_TYPE))) { jsonMimeTypes.add(consume); - } - else + } else prioritizedContentTypes.add(consume); consume.put("hasMore", "true"); @@ -434,7 +431,7 @@ else if ( isJsonMimeType(consume.get(MEDIA_TYPE))) { prioritizedContentTypes.addAll(0, jsonMimeTypes); prioritizedContentTypes.addAll(0, jsonVendorMimeTypes); - prioritizedContentTypes.get(prioritizedContentTypes.size()-1).put("hasMore", null); + prioritizedContentTypes.get(prioritizedContentTypes.size() - 1).put("hasMore", null); return prioritizedContentTypes; } @@ -452,14 +449,14 @@ private static boolean isMultipartType(List> consumes) { @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); - if(!BooleanUtils.toBoolean(model.isEnum)) { + if (!BooleanUtils.toBoolean(model.isEnum)) { //final String lib = getLibrary(); //Needed imports for Jackson based libraries - if(additionalProperties.containsKey("jackson")) { + if (additionalProperties.containsKey("jackson")) { model.imports.add("JsonProperty"); model.imports.add("JsonValue"); } - if(additionalProperties.containsKey("gson")) { + if (additionalProperties.containsKey("gson")) { model.imports.add("SerializedName"); model.imports.add("TypeAdapter"); model.imports.add("JsonAdapter"); @@ -469,7 +466,7 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } } else { // enum class //Needed imports for Jackson's JsonCreator - if(additionalProperties.containsKey("jackson")) { + if (additionalProperties.containsKey("jackson")) { model.imports.add("JsonValue"); model.imports.add("JsonCreator"); } @@ -480,13 +477,13 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert @Override public Map postProcessAllModels(Map objs) { Map allProcessedModels = super.postProcessAllModels(objs); - if(!additionalProperties.containsKey("gsonFactoryMethod")) { + if (!additionalProperties.containsKey("gsonFactoryMethod")) { List allModels = new ArrayList(); - for (String name: allProcessedModels.keySet()) { - Map models = (Map)allProcessedModels.get(name); + for (String name : allProcessedModels.keySet()) { + Map models = (Map) allProcessedModels.get(name); try { allModels.add(((List) models.get("models")).get(0)); - } catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } } @@ -500,7 +497,7 @@ public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); //Needed import for Gson based libraries if (additionalProperties.containsKey("gson")) { - List> imports = (List>)objs.get("imports"); + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -517,13 +514,13 @@ public Map postProcessModelsEnum(Map objs) { return objs; } - private List> modelInheritanceSupportInGson(List allModels) { + public static List> modelInheritanceSupportInGson(List allModels) { LinkedListMultimap byParent = LinkedListMultimap.create(); for (Object m : allModels) { Map entry = (Map) m; - CodegenModel parent = ((CodegenModel)entry.get("model")).parentModel; - if(null!= parent) { - byParent.put(parent, ((CodegenModel)entry.get("model"))); + CodegenModel parent = ((CodegenModel) entry.get("model")).parentModel; + if (null != parent) { + byParent.put(parent, ((CodegenModel) entry.get("model"))); } } List> parentsList = new ArrayList<>(); @@ -593,19 +590,19 @@ public void setUseRuntimeException(boolean useRuntimeException) { /** * Check if the given MIME is a JSON MIME. * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON */ static boolean isJsonMimeType(String mime) { - return mime != null && ( JSON_MIME_PATTERN.matcher(mime).matches()); + return mime != null && (JSON_MIME_PATTERN.matcher(mime).matches()); } /** * Check if the given MIME is a JSON Vendor MIME. * JSON MIME examples: - * application/vnd.mycompany+json - * application/vnd.mycompany.resourceA.version1+json + * application/vnd.mycompany+json + * application/vnd.mycompany.resourceA.version1+json */ static boolean isJsonVendorMimeType(String mime) { return mime != null && JSON_VENDOR_MIME_PATTERN.matcher(mime).matches(); 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 ee22e1cb3254..591d149fa4fd 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 @@ -1,14 +1,8 @@ package org.openapitools.codegen.languages; -import com.fasterxml.jackson.core.JsonProcessingException; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.SupportingFile; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.util.Yaml; +import org.openapitools.codegen.*; +import io.swagger.v3.oas.models.*; + import org.apache.commons.lang3.BooleanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -24,6 +18,7 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen { protected String title = "Swagger Inflector"; protected String implFolder = "src/main/java"; + public JavaInflectorServerCodegen() { super(); @@ -56,7 +51,7 @@ public CodegenType getTag() { @Override public String getName() { - return "inflector"; + return "java-inflector"; } @Override @@ -72,9 +67,9 @@ public void processOpts() { writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); writeOptional(outputFolder, new SupportingFile("web.mustache", "src/main/webapp/WEB-INF", "web.xml")); writeOptional(outputFolder, new SupportingFile("inflector.mustache", "", "inflector.yaml")); - supportingFiles.add(new SupportingFile("swagger.mustache", - "src/main/swagger", - "swagger.yaml") + supportingFiles.add(new SupportingFile("openapi.mustache", + "src/main/openapi", + "openapi.yaml") ); supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + invokerPackage).replace(".", "/"), "StringUtil.java")); @@ -148,10 +143,10 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert super.postProcessModelProperty(model, property); //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { + if (!BooleanUtils.toBoolean(model.isEnum)) { model.imports.add("JsonProperty"); - if(BooleanUtils.toBoolean(model.hasEnums)) { + if (BooleanUtils.toBoolean(model.hasEnums)) { model.imports.add("JsonValue"); } } @@ -162,7 +157,7 @@ public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); //Add imports for Jackson - List> imports = (List>)objs.get("imports"); + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -187,7 +182,7 @@ protected String getOrGenerateOperationId(Operation operation, String path, Stri public String apiFilename(String templateName, String tag) { String result = super.apiFilename(templateName, tag); - if ( templateName.endsWith("api.mustache") ) { + if (templateName.endsWith("api.mustache")) { int ix = result.indexOf(sourceFolder); String beg = result.substring(0, ix); String end = result.substring(ix + sourceFolder.length()); @@ -199,14 +194,7 @@ public String apiFilename(String templateName, String tag) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { - try { - objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } + generateYAMLSpecFile(objs); return super.postProcessSupportingFileData(objs); } @@ -216,6 +204,6 @@ public String toApiName(String name) { return "DefaultController"; } name = name.replaceAll("[^a-zA-Z0-9]+", "_"); - return camelize(name)+ "Controller"; + return camelize(name) + "Controller"; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java index 697a974fa360..28bebad079ff 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java @@ -1,10 +1,10 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.*; import org.openapitools.codegen.languages.features.BeanValidationFeatures; +import org.openapitools.codegen.languages.features.JbossFeature; +import org.openapitools.codegen.languages.features.SwaggerFeatures; +import io.swagger.v3.oas.models.*; import java.io.File; @@ -16,9 +16,9 @@ * to get an instance of ServiceImpl that implements the Service interface. */ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen implements BeanValidationFeatures { - + protected boolean useBeanValidation = true; - + /** * Default constructor */ @@ -37,7 +37,7 @@ public JavaJAXRSCXFCDIServerCodegen() { // Updated template directory embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-cdi"; - + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); } @@ -57,7 +57,7 @@ public void processOpts() { if (useBeanValidation) { writePropertyBack(USE_BEANVALIDATION, useBeanValidation); } - + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen // writeOptional means these files are only written if they don't already exist 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 912137b27a8d..35c17a9844d6 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 @@ -9,18 +9,14 @@ import org.apache.commons.io.FileUtils; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.SupportingFile; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.util.Json; - -public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen -{ +import org.openapitools.codegen.*; +import org.openapitools.codegen.languages.features.BeanValidationFeatures; +import org.openapitools.codegen.languages.features.JbossFeature; +import org.openapitools.codegen.languages.features.SwaggerFeatures; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.core.util.Json; + +public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { public static final String INTERFACE_ONLY = "interfaceOnly"; public static final String RETURN_RESPONSE = "returnResponse"; @@ -30,8 +26,7 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen private boolean returnResponse = false; private boolean generatePom = true; - public JavaJAXRSSpecServerCodegen() - { + public JavaJAXRSSpecServerCodegen() { super(); invokerPackage = "io.swagger.api"; artifactId = "swagger-jaxrs-server"; @@ -59,8 +54,8 @@ public JavaJAXRSSpecServerCodegen() super.embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "spec"; - for ( int i = 0; i < cliOptions.size(); i++ ) { - if ( CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt()) ) { + for (int i = 0; i < cliOptions.size(); i++) { + if (CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt())) { cliOptions.remove(i); break; } @@ -69,7 +64,7 @@ public JavaJAXRSSpecServerCodegen() CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setDefault(DEFAULT_LIBRARY); - Map supportedLibraries = new LinkedHashMap(); + Map supportedLibraries = new LinkedHashMap(); supportedLibraries.put(DEFAULT_LIBRARY, "JAXRS"); library.setEnum(supportedLibraries); @@ -81,8 +76,7 @@ public JavaJAXRSSpecServerCodegen() } @Override - public void processOpts() - { + public void processOpts() { if (additionalProperties.containsKey(GENERATE_POM)) { generatePom = Boolean.valueOf(additionalProperties.get(GENERATE_POM).toString()); } @@ -113,12 +107,16 @@ public void processOpts() writeOptional(outputFolder, new SupportingFile("RestApplication.mustache", (sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java")); } + + supportingFiles.add(new SupportingFile("openapi.mustache", + "src/main/openapi", + "openapi.yaml") + ); } @Override - public String getName() - { + public String getName() { return "jaxrs-spec"; } @@ -162,20 +160,13 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } @Override - public void preprocessSwagger(Swagger swagger) { - //copy input swagger to output folder - try { - String swaggerJson = Json.pretty(swagger); - FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson); - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e.getCause()); - } - super.preprocessSwagger(swagger); - + public Map postProcessSupportingFileData(Map objs) { + generateJSONSpecFile(objs); + return super.postProcessSupportingFileData(objs); } + @Override - public String getHelp() - { + public String getHelp() { return "Generates a Java JAXRS Server according to JAXRS 2.0 specification."; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java index 61a852daf73d..612db8032ab5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java @@ -2,7 +2,7 @@ import org.openapitools.codegen.*; import org.openapitools.codegen.languages.features.BeanValidationFeatures; -import io.swagger.models.Operation; +import io.swagger.v3.oas.models.*; import java.util.*; @@ -13,7 +13,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { protected static final String LIBRARY_JERSEY1 = "jersey1"; protected static final String LIBRARY_JERSEY2 = "jersey2"; - + /** * Default library template to use. (Default:{@value #DEFAULT_LIBRARY}) */ @@ -53,29 +53,27 @@ public JavaJerseyServerCodegen() { } @Override - public String getName() - { - return "jaxrs"; // TODO should be renamed as "jaxrs-jersey" + public String getName() { + return "jaxrs-jersey"; } @Override - public String getHelp() - { + public String getHelp() { return "Generates a Java JAXRS Server application based on Jersey framework."; } @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); - if("null".equals(property.example)) { + if ("null".equals(property.example)) { property.example = null; } //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { + if (!BooleanUtils.toBoolean(model.isEnum)) { model.imports.add("JsonProperty"); - if(BooleanUtils.toBoolean(model.hasEnums)) { + if (BooleanUtils.toBoolean(model.hasEnums)) { model.imports.add("JsonValue"); } } @@ -89,11 +87,11 @@ public void processOpts() { if (StringUtils.isEmpty(library)) { setLibrary(DEFAULT_LIBRARY); } - - if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { + + if (additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); } - + if (additionalProperties.containsKey(USE_TAGS)) { this.setUseTags(Boolean.valueOf(additionalProperties.get(USE_TAGS).toString())); } @@ -101,7 +99,7 @@ public void processOpts() { if ("joda".equals(dateLibrary)) { supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); - } else if ( dateLibrary.startsWith("java8") ) { + } else if (dateLibrary.startsWith("java8")) { supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "OffsetDateTimeProvider.java")); supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); } @@ -125,7 +123,7 @@ public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); //Add imports for Jackson - List> imports = (List>)objs.get("imports"); + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -146,7 +144,7 @@ public Map postProcessModelsEnum(Map objs) { public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { if (useTags) { super.addOperationToGroup(tag, resourcePath, operation, co, operations); - } else { + } else { String basePath = resourcePath; if (basePath.startsWith("/")) { basePath = basePath.substring(1); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaMSF4JServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaMSF4JServerCodegen.java index c6f3e7ab2751..eaaf3e6a22a5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaMSF4JServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaMSF4JServerCodegen.java @@ -1,7 +1,12 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.*; -import io.swagger.models.Operation; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.SupportingFile; +import io.swagger.v3.oas.models.Operation; import java.util.*; @@ -22,7 +27,7 @@ public JavaMSF4JServerCodegen() { apiTemplateFiles.put("apiService.mustache", ".java"); apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); apiTemplateFiles.put("apiServiceFactory.mustache", ".java"); - apiTestTemplateFiles.clear(); + apiTestTemplateFiles.clear(); modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); embeddedTemplateDir = templateDir = "MSF4J"; @@ -36,29 +41,27 @@ public JavaMSF4JServerCodegen() { } @Override - public String getName() - { - return "msf4j"; + public String getName() { + return "java-msf4j"; } @Override - public String getHelp() - { + public String getHelp() { return "Generates a Java Micro Service based on WSO2 Microservices Framework for Java (MSF4J)"; } @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); - if("null".equals(property.example)) { + if ("null".equals(property.example)) { property.example = null; } //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { + if (!BooleanUtils.toBoolean(model.isEnum)) { model.imports.add("JsonProperty"); - if(BooleanUtils.toBoolean(model.hasEnums)) { + if (BooleanUtils.toBoolean(model.hasEnums)) { model.imports.add("JsonValue"); } } @@ -73,14 +76,14 @@ public void processOpts() { setLibrary(DEFAULT_LIBRARY); } - if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { + if (additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); } if ("joda".equals(dateLibrary)) { supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); - } else if ( dateLibrary.startsWith("java8") ) { + } else if (dateLibrary.startsWith("java8")) { supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "OffsetDateTimeProvider.java")); supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); } @@ -104,7 +107,7 @@ public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); //Add imports for Jackson - List> imports = (List>)objs.get("imports"); + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; 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 880aafa0dd55..a0e8026d201f 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 @@ -1,6 +1,7 @@ package org.openapitools.codegen.languages; import java.io.File; +import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -9,19 +10,18 @@ import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenResponse; import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.CodegenOperation; import org.openapitools.codegen.CodegenParameter; import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenResponse; import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.Swagger; -import io.swagger.models.Tag; -import io.swagger.models.parameters.FormParameter; -import io.swagger.models.parameters.Parameter; +import org.openapitools.codegen.utils.URLPathUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.tags.Tag; /** * Created by prokarma on 04/09/17. @@ -82,7 +82,7 @@ public JavaPKMSTServerCodegen() { // Middleware config this.cliOptions.add(new CliOption("pkmstInterceptor", "PKMST Interceptor")); this.apiTestTemplateFiles.put("api_test.mustache", ".java"); - + if (".md".equals(this.modelDocTemplateFiles.get("model_doc.mustache"))) { this.modelDocTemplateFiles.remove("model_doc.mustache"); } @@ -91,32 +91,6 @@ public JavaPKMSTServerCodegen() { } } - private static String getAccept(Operation operation) { - String accepts = null; - String defaultContentType = "application/json"; - if (operation.getProduces() != null && !operation.getProduces().isEmpty()) { - StringBuilder sb = new StringBuilder(); - for (String produces : operation.getProduces()) { - if (defaultContentType.equalsIgnoreCase(produces)) { - accepts = defaultContentType; - break; - } else { - if (sb.length() > 0) { - sb.append(","); - } - sb.append(produces); - } - } - if (accepts == null) { - accepts = sb.toString(); - } - } else { - accepts = defaultContentType; - } - - return accepts; - } - public CodegenType getTag() { return CodegenType.SERVER; } @@ -291,17 +265,17 @@ public void processOpts() { this.supportingFiles.add(new SupportingFile( "cucumber" + File.separator + "cucumberTest.mustache", this.testFolder + File.separator - + this.basePackage.replace(".", File.separator) + File.separator + "cucumber", + + this.basePackage.replace(".", File.separator) + File.separator + "cucumber", serviceName + "Test.java")); this.supportingFiles.add(new SupportingFile( "cucumber" + File.separator + "cucumberSteps.mustache", this.testFolder + File.separator - + this.basePackage.replace(".", File.separator) + File.separator + "cucumber", + + this.basePackage.replace(".", File.separator) + File.separator + "cucumber", serviceName + "Steps.java")); this.supportingFiles.add(new SupportingFile( "cucumber" + File.separator + "package.mustache", this.testFolder + File.separator - + this.basePackage.replace(".", File.separator) + File.separator + "cucumber", + + this.basePackage.replace(".", File.separator) + File.separator + "cucumber", serviceName + "package-info.java")); // test resources @@ -326,13 +300,13 @@ public void processOpts() { this.supportingFiles.add(new SupportingFile( "gatling" + File.separator + "testapi.mustache", ("src") + File.separator + ("test") + File.separator - + ("scala") + File.separator + ("scalaFiles").replace(".", java.io.File.separator), + + ("scala") + File.separator + ("scalaFiles").replace(".", java.io.File.separator), "testapi.scala")); // adding class for integration test this.supportingFiles.add(new SupportingFile( "integration" + File.separator + "integrationtest.mustache", this.testFolder + File.separator - + this.basePackage.replace(".", File.separator) + File.separator + "controller", + + this.basePackage.replace(".", File.separator) + File.separator + "controller", serviceName + "IT.java")); } @@ -386,8 +360,7 @@ public void setReturnContainer(final String returnContainer) { * This method removes header parameters from the list of parameters and * also corrects last allParams hasMore state. * - * @param allParams - * list of all parameters + * @param allParams list of all parameters */ private void removeHeadersFromAllParams(List allParams) { if (allParams.isEmpty()) { @@ -405,11 +378,9 @@ private void removeHeadersFromAllParams(List allParams) { } /** - * @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. + * @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(String returnType, DataTypeAssigner dataTypeAssigner) { final String rt = returnType; @@ -485,14 +456,14 @@ public Map postProcessModelsEnum(Map objs) { @SuppressWarnings("unchecked") @Override - public void preprocessSwagger(Swagger swagger) { - super.preprocessSwagger(swagger); - if (swagger == null || swagger.getPaths() == null) { + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); + if (openAPI == null || openAPI.getPaths() == null) { return; } - if (swagger.getTags() != null) { + if (openAPI.getTags() != null) { List resourcePaths = new ArrayList<>(); - for (Tag tag : swagger.getTags()) { + for (Tag tag : openAPI.getTags()) { ResourcePath resourcePath = new ResourcePath(); resourcePath.setPath(tag.getName()); resourcePaths.add(resourcePath); @@ -501,7 +472,7 @@ public void preprocessSwagger(Swagger swagger) { } // get vendor extensions - Map vendorExt = swagger.getInfo().getVendorExtensions(); + Map vendorExt = openAPI.getInfo().getExtensions(); if (vendorExt != null && !vendorExt.toString().equals("")) { if (vendorExt.containsKey("x-codegen")) { @@ -525,39 +496,38 @@ public void preprocessSwagger(Swagger swagger) { } } - for (String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if (path.getOperations() == null) { + /* comment out below as it's already done in AbstractJavaCodegen + for (String pathname : openAPI.getPaths().keySet()) { + PathItem path = openAPI.getPaths().get(pathname); + if (path.readOperations() == null) { continue; } - for (Operation operation : path.getOperations()) { - boolean hasFormParameters = false; - for (Parameter parameter : operation.getParameters()) { - if (parameter instanceof FormParameter) { - hasFormParameters = true; - } - } + for (Operation operation : path.readOperations()) { + boolean hasFormParameters = hasFormParameter(operation); + // only add content-Type if its no a GET-Method if (path.getGet() != null || !operation.equals(path.getGet())) { String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json"; - String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty() - ? defaultContentType : operation.getConsumes().get(0); - operation.setVendorExtension("x-contentType", contentType); + List consumes = new ArrayList(getConsumesInfo(operation)); + String contentType = consumes == null || consumes.isEmpty() ? defaultContentType : consumes.get(0); + operation.addExtension("x-contentType", contentType); } String accepts = getAccept(operation); - operation.setVendorExtension("x-accepts", accepts); + operation.addExtension("x-accepts", accepts); } - } + }*/ - if ("/".equals(swagger.getBasePath())) { - swagger.setBasePath(""); + /* TODO the following logic shouldn't need any more + if ("/".equals(openAPI.getBasePath())) { + openAPI.setBasePath(""); } + */ if (!additionalProperties.containsKey(TITLE)) { // From the title, compute a reasonable name for the package and the // API - String title = swagger.getInfo().getTitle(); + String title = openAPI.getInfo().getTitle(); // Drop any API suffix if (title != null) { @@ -571,21 +541,16 @@ public void preprocessSwagger(Swagger swagger) { additionalProperties.put(TITLE, this.title); } - String host = swagger.getHost(); - String port = "8008"; - if (host != null) { - String[] parts = host.split(":"); - if (parts.length > 1) { - port = parts[1]; - } - } + URL url = URLPathUtils.getServerURL(openAPI); + String host = url.getHost(); + Integer port = url.getPort(); this.additionalProperties.put("serverPort", port); - if (swagger.getPaths() != null) { - for (String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if (path.getOperations() != null) { - for (Operation operation : path.getOperations()) { + if (openAPI.getPaths() != null) { + for (String pathname : openAPI.getPaths().keySet()) { + PathItem path = openAPI.getPaths().get(pathname); + if (path.readOperations() != null) { + for (Operation operation : path.readOperations()) { if (operation.getTags() != null) { List> tags = new ArrayList>(); for (String tag : operation.getTags()) { @@ -601,7 +566,7 @@ public void preprocessSwagger(Swagger swagger) { String tag = operation.getTags().get(0); operation.setTags(Arrays.asList(tag)); } - operation.setVendorExtension("x-tags", tags); + operation.addExtension("x-tags", tags); } } } @@ -611,7 +576,7 @@ public void preprocessSwagger(Swagger swagger) { @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, - Map> operations) { + Map> operations) { super.addOperationToGroup(tag, resourcePath, operation, co, operations); co.subresourceOperation = !co.path.isEmpty(); } 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 31940ba25ef6..1dc4c642997a 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 @@ -1,11 +1,13 @@ package org.openapitools.codegen.languages; -import com.fasterxml.jackson.core.JsonProcessingException; import org.openapitools.codegen.*; -import org.openapitools.codegen.languages.features.BeanValidationFeatures; -import io.swagger.models.Model; -import io.swagger.models.Swagger; -import io.swagger.util.Json; +import org.openapitools.codegen.languages.features.*; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.core.util.Json; + import java.io.File; import java.util.List; @@ -161,11 +163,11 @@ public void processOpts() { supportingFiles.add(new SupportingFile("errorHandler.mustache", "app/swagger", "ErrorHandler.java")); } - if(this.wrapCalls) { + if (this.wrapCalls) { supportingFiles.add(new SupportingFile("apiCall.mustache", "app/swagger", "ApiCall.java")); } - if(this.useSwaggerUI) { + if (this.useSwaggerUI) { //App/Controllers supportingFiles.add(new SupportingFile("swagger.mustache", "public", "swagger.json")); supportingFiles.add(new SupportingFile("apiDocController.mustache", String.format("app/%s", apiPackage.replace(".", File.separator)), "ApiDocController.java")); @@ -202,9 +204,9 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); - if(codegenModel.description != null) { + if (codegenModel.description != null) { codegenModel.imports.remove("ApiModel"); } return codegenModel; @@ -222,7 +224,9 @@ public void setBasePackage(String configPackage) { this.basePackage = configPackage; } - public void setControllerOnly(boolean controllerOnly) { this.controllerOnly = controllerOnly; } + public void setControllerOnly(boolean controllerOnly) { + this.controllerOnly = controllerOnly; + } public void setUseInterfaces(boolean useInterfaces) { this.useInterfaces = useInterfaces; @@ -318,15 +322,7 @@ private CliOption createBooleanCliWithDefault(String optionName, String descript @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - System.out.println("swagger" + swagger.toString()); - if(swagger != null) { - try { - objs.put("swagger-json", Json.pretty().writeValueAsString(swagger)); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } + generateJSONSpecFile(objs); return super.postProcessSupportingFileData(objs); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyEapServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyEapServerCodegen.java index 84c70caeaea8..4fae951d2fc0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyEapServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyEapServerCodegen.java @@ -6,18 +6,13 @@ import java.util.List; import java.util.Map; -import org.apache.commons.lang3.BooleanUtils; - -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenResponse; -import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.*; import org.openapitools.codegen.languages.features.BeanValidationFeatures; import org.openapitools.codegen.languages.features.JbossFeature; import org.openapitools.codegen.languages.features.SwaggerFeatures; -import io.swagger.models.Operation; +import io.swagger.v3.oas.models.*; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; public class JavaResteasyEapServerCodegen extends AbstractJavaJAXRSServerCodegen implements JbossFeature, BeanValidationFeatures, SwaggerFeatures { @@ -25,7 +20,7 @@ public class JavaResteasyEapServerCodegen extends AbstractJavaJAXRSServerCodegen protected boolean useBeanValidation = true; protected boolean generateJbossDeploymentDescriptor = true; protected boolean useSwaggerFeature = false; - + public JavaResteasyEapServerCodegen() { super(); @@ -119,7 +114,7 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera } else { if (co.path.startsWith("/" + basePath)) { co.path = co.path.substring(("/" + basePath).length()); - } + } co.subresourceOperation = !co.path.isEmpty(); } List opList = operations.get(basePath); @@ -144,9 +139,9 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert if (BooleanUtils.toBoolean(model.hasEnums)) { model.imports.add("JsonValue"); + } } } - } @Override public Map postProcessModelsEnum(Map objs) { @@ -164,12 +159,12 @@ public Map postProcessModelsEnum(Map objs) { Map item = new HashMap(); item.put("import", importMapping.get("JsonValue")); imports.add(item); - } + } } return objs; } - + public void setUseBeanValidation(boolean useBeanValidation) { this.useBeanValidation = useBeanValidation; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyServerCodegen.java index ca442cb758ab..552a84cc08d8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyServerCodegen.java @@ -3,7 +3,7 @@ import org.openapitools.codegen.*; import org.openapitools.codegen.languages.features.BeanValidationFeatures; import org.openapitools.codegen.languages.features.JbossFeature; -import io.swagger.models.Operation; +import io.swagger.v3.oas.models.*; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; @@ -13,7 +13,7 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen implements JbossFeature { protected boolean generateJbossDeploymentDescriptor = true; - + public JavaResteasyServerCodegen() { super(); @@ -58,7 +58,7 @@ public void processOpts() { GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp); } - + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("gradle.mustache", "", "build.gradle")); writeOptional(outputFolder, new SupportingFile("settingsGradle.mustache", "", "settings.gradle")); @@ -76,7 +76,7 @@ public void processOpts() { if (generateJbossDeploymentDescriptor) { writeOptional(outputFolder, new SupportingFile("jboss-web.mustache", - ("src/main/webapp/WEB-INF"), "jboss-web.xml")); + ("src/main/webapp/WEB-INF"), "jboss-web.xml")); } writeOptional(outputFolder, new SupportingFile("RestApplication.mustache", @@ -137,10 +137,10 @@ public Map postProcessOperations(Map objs) { @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { + if (!BooleanUtils.toBoolean(model.isEnum)) { model.imports.add("JsonProperty"); - if(BooleanUtils.toBoolean(model.hasEnums)) { + if (BooleanUtils.toBoolean(model.hasEnums)) { model.imports.add("JsonValue"); } } @@ -151,7 +151,7 @@ public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); //Add imports for Jackson - List> imports = (List>)objs.get("imports"); + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -167,7 +167,7 @@ public Map postProcessModelsEnum(Map objs) { return objs; } - + public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor) { this.generateJbossDeploymentDescriptor = generateJbossDeploymentDescriptor; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/UndertowCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java similarity index 73% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/UndertowCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java index 4c3564d56192..1570197a0442 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/UndertowCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java @@ -1,26 +1,21 @@ package org.openapitools.codegen.languages; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import org.openapitools.codegen.*; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.util.Json; -import io.swagger.util.Yaml; + import org.apache.commons.lang3.BooleanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; import java.util.*; -public class UndertowCodegen extends AbstractJavaCodegen { +public class JavaUndertowServerCodegen extends AbstractJavaCodegen { - private static final Logger LOGGER = LoggerFactory.getLogger(UndertowCodegen.class); + private static final Logger LOGGER = LoggerFactory.getLogger(JavaUndertowServerCodegen.class); - protected String title = "Swagger Undertow Server"; + protected String title = "OpenAPI Undertow Server"; protected String implFolder = "src/main/java"; - public UndertowCodegen() { + + public JavaUndertowServerCodegen() { super(); sourceFolder = "src/main/java"; @@ -50,12 +45,12 @@ public CodegenType getTag() { @Override public String getName() { - return "undertow"; + return "java-undertow-server"; } @Override public String getHelp() { - return "Generates a Java Undertow Server application."; + return "Generates a Java Undertow Server application (beta)."; } @Override @@ -68,7 +63,7 @@ public void processOpts() { writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); // keep the yaml in config folder for framework validation. - supportingFiles.add(new SupportingFile("swagger.mustache", ("src.main.resources.config").replace(".", java.io.File.separator), "swagger.json")); + supportingFiles.add(new SupportingFile("openapi.mustache", ("src.main.resources.config").replace(".", java.io.File.separator), "openapi.json")); supportingFiles.add(new SupportingFile("handler.mustache", ("src.main.java.io.swagger.handler").replace(".", java.io.File.separator), "PathHandlerProvider.java")); supportingFiles.add(new SupportingFile("service.mustache", ("src.main.resources.META-INF.services").replace(".", java.io.File.separator), "com.networknt.server.HandlerProvider")); @@ -79,36 +74,6 @@ public void processOpts() { } - /* - @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - String basePath = resourcePath; - if (basePath.startsWith("/")) { - basePath = basePath.substring(1); - } - int pos = basePath.indexOf("/"); - if (pos > 0) { - basePath = basePath.substring(0, pos); - } - - if (basePath == "") { - basePath = "default"; - } else { - if (co.path.startsWith("/" + basePath)) { - co.path = co.path.substring(("/" + basePath).length()); - } - co.subresourceOperation = !co.path.isEmpty(); - } - List opList = operations.get(basePath); - if (opList == null) { - opList = new ArrayList(); - operations.put(basePath, opList); - } - opList.add(co); - co.baseName = basePath; - } - */ - @Override public Map postProcessOperations(Map objs) { Map operations = (Map) objs.get("operations"); @@ -149,10 +114,10 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert super.postProcessModelProperty(model, property); //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { + if (!BooleanUtils.toBoolean(model.isEnum)) { model.imports.add("JsonProperty"); - if(BooleanUtils.toBoolean(model.hasEnums)) { + if (BooleanUtils.toBoolean(model.hasEnums)) { model.imports.add("JsonValue"); } } @@ -163,7 +128,7 @@ public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); //Add imports for Jackson - List> imports = (List>)objs.get("imports"); + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -183,7 +148,7 @@ public Map postProcessModelsEnum(Map objs) { public String apiFilename(String templateName, String tag) { String result = super.apiFilename(templateName, tag); - if ( templateName.endsWith("api.mustache") ) { + if (templateName.endsWith("api.mustache")) { int ix = result.indexOf(sourceFolder); String beg = result.substring(0, ix); String end = result.substring(ix + sourceFolder.length()); @@ -195,16 +160,7 @@ public String apiFilename(String templateName, String tag) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - System.out.println("swagger" + swagger.toString()); - if(swagger != null) { - try { - //objs.put("swagger-json", Json.mapper().writeValueAsString(swagger)); - objs.put("swagger-json", Json.pretty().writeValueAsString(swagger)); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } + generateJSONSpecFile(objs); return super.postProcessSupportingFileData(objs); } @@ -214,6 +170,6 @@ public String toApiName(String name) { 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 camelize(name) + "Handler"; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java index 7bf8cd426481..a0826cabfe5e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java @@ -6,14 +6,16 @@ import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.HttpMethod; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.Swagger; -import io.swagger.util.Json; +import org.openapitools.codegen.utils.URLPathUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.core.util.Json; import java.io.File; +import java.net.URL; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -33,10 +35,10 @@ public class JavaVertXServerCodegen extends AbstractJavaCodegen { /** * A Java Vert.X generator. It uses java8 date API. It can be configured with 2 CLI options : - * + *

* rxInterface : type Boolean if true, API interfaces are generated with RX and methods return * Single and Comparable. default : false - * + *

* vertxSwaggerRouterVersion : type String Specify the version of the swagger router library */ public JavaVertXServerCodegen() { @@ -173,38 +175,37 @@ public Map postProcessOperations(Map objs) { @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, - Map definitions, Swagger swagger) { + Map definitions, OpenAPI openAPI) { CodegenOperation codegenOperation = - super.fromOperation(path, httpMethod, operation, definitions, swagger); + super.fromOperation(path, httpMethod, operation, definitions, openAPI); codegenOperation.imports.add("MainApiException"); return codegenOperation; } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); codegenModel.imports.remove("ApiModel"); codegenModel.imports.remove("ApiModelProperty"); return codegenModel; - } @Override - public void preprocessSwagger(Swagger swagger) { - super.preprocessSwagger(swagger); + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); // add full swagger definition in a mustache parameter - String swaggerDef = Json.pretty(swagger); - this.additionalProperties.put("fullSwagger", swaggerDef); + String openAPIDef = Json.pretty(openAPI); + this.additionalProperties.put("fullOpenAPI", openAPIDef); // add server port from the swagger file, 8080 by default - String host = swagger.getHost(); - String port = extractPortFromHost(host); + URL url = URLPathUtils.getServerURL(openAPI); + Integer port = url.getPort(); this.additionalProperties.put("serverPort", port); // retrieve api version from swagger file, 1.0.0-SNAPSHOT by default - if (swagger.getInfo() != null && swagger.getInfo().getVersion() != null) { - artifactVersion = apiVersion = swagger.getInfo().getVersion(); + if (openAPI.getInfo() != null && openAPI.getInfo().getVersion() != null) { + artifactVersion = apiVersion = openAPI.getInfo().getVersion(); } else { artifactVersion = apiVersion; } @@ -213,24 +214,24 @@ public void preprocessSwagger(Swagger swagger) { * manage operation & custom serviceId because operationId field is not * required and may be empty */ - Map paths = swagger.getPaths(); + Map paths = openAPI.getPaths(); if (paths != null) { - for (Entry entry : paths.entrySet()) { + for (Entry entry : paths.entrySet()) { manageOperationNames(entry.getValue(), entry.getKey()); } } this.additionalProperties.remove("gson"); } - private void manageOperationNames(Path path, String pathname) { + private void manageOperationNames(PathItem path, String pathname) { String serviceIdTemp; - Map operationMap = path.getOperationMap(); + Map operationMap = path.readOperationsMap(); if (operationMap != null) { for (Entry entry : operationMap.entrySet()) { serviceIdTemp = computeServiceId(pathname, entry); - entry.getValue().setVendorExtension("x-serviceid", serviceIdTemp); - entry.getValue().setVendorExtension("x-serviceid-varname", + entry.getValue().addExtension("x-serviceid", serviceIdTemp); + entry.getValue().addExtension("x-serviceid-varname", serviceIdTemp.toUpperCase() + "_SERVICE_ID"); } } @@ -240,7 +241,7 @@ private String computeServiceId(String pathname, Entry en String operationId = entry.getValue().getOperationId(); return (operationId != null) ? operationId : entry.getKey().name() - + pathname.replaceAll("-", "_").replaceAll("/", "_").replaceAll("[{}]", ""); + + pathname.replaceAll("-", "_").replaceAll("/", "_").replaceAll("[{}]", ""); } protected String extractPortFromHost(String host) { 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 748625e455de..b7cb4cc73034 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 @@ -12,25 +12,14 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.SupportingFile; import org.openapitools.codegen.DefaultCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Info; -import io.swagger.models.License; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.oas.models.info.*; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -58,25 +47,25 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo public static final String EMIT_JS_DOC = "emitJSDoc"; public static final String USE_ES6 = "useES6"; - final String[][] JAVASCRIPT_SUPPORTING_FILES = new String[][] { - new String[] {"package.mustache", "package.json"}, - new String[] {"index.mustache", "src/index.js"}, - new String[] {"ApiClient.mustache", "src/ApiClient.js"}, - new String[] {"git_push.sh.mustache", "git_push.sh"}, - new String[] {"README.mustache", "README.md"}, - new String[] {"mocha.opts", "mocha.opts"}, - new String[] {"travis.yml", ".travis.yml"} + final String[][] JAVASCRIPT_SUPPORTING_FILES = new String[][]{ + new String[]{"package.mustache", "package.json"}, + new String[]{"index.mustache", "src/index.js"}, + new String[]{"ApiClient.mustache", "src/ApiClient.js"}, + new String[]{"git_push.sh.mustache", "git_push.sh"}, + new String[]{"README.mustache", "README.md"}, + new String[]{"mocha.opts", "mocha.opts"}, + new String[]{"travis.yml", ".travis.yml"} }; - final String[][] JAVASCRIPT_ES6_SUPPORTING_FILES = new String[][] { - new String[] {"package.mustache", "package.json"}, - new String[] {"index.mustache", "src/index.js"}, - new String[] {"ApiClient.mustache", "src/ApiClient.js"}, - new String[] {"git_push.sh.mustache", "git_push.sh"}, - new String[] {"README.mustache", "README.md"}, - new String[] {"mocha.opts", "mocha.opts"}, - new String[] {"travis.yml", ".travis.yml"}, - new String[] {".babelrc.mustache", ".babelrc"} + final String[][] JAVASCRIPT_ES6_SUPPORTING_FILES = new String[][]{ + new String[]{"package.mustache", "package.json"}, + new String[]{"index.mustache", "src/index.js"}, + new String[]{"ApiClient.mustache", "src/ApiClient.js"}, + new String[]{"git_push.sh.mustache", "git_push.sh"}, + new String[]{"README.mustache", "README.md"}, + new String[]{"mocha.opts", "mocha.opts"}, + new String[]{"travis.yml", ".travis.yml"}, + new String[]{".babelrc.mustache", ".babelrc"} }; protected String projectName; @@ -111,6 +100,9 @@ public JavascriptClientCodegen() { modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + // reference: http://www.w3schools.com/js/js_reserved.asp setReservedWordsLowerCase( Arrays.asList( @@ -159,6 +151,7 @@ public JavascriptClientCodegen() { typeMapping.put("object", "Object"); typeMapping.put("integer", "Number"); // binary not supported in JavaScript client right now, using String as a workaround + // TODO revise the logic below typeMapping.put("ByteArray", "Blob"); // I don't see ByteArray defined in the Swagger docs. typeMapping.put("binary", "Blob"); typeMapping.put("UUID", "String"); @@ -192,7 +185,7 @@ public JavascriptClientCodegen() { cliOptions.add(new CliOption(USE_INHERITANCE, "use JavaScript prototype chains & delegation for inheritance") .defaultValue(Boolean.TRUE.toString())); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(USE_ES6, "use JavaScript ES6 (ECMAScript 6) (beta). Default is ES5.") @@ -223,14 +216,6 @@ public void processOpts() { } super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - if (additionalProperties.containsKey(PROJECT_NAME)) { setProjectName(((String) additionalProperties.get(PROJECT_NAME))); } @@ -273,11 +258,11 @@ public void processOpts() { } @Override - public void preprocessSwagger(Swagger swagger) { - super.preprocessSwagger(swagger); + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); - if (swagger.getInfo() != null) { - Info info = swagger.getInfo(); + if (openAPI.getInfo() != null) { + 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())); @@ -340,14 +325,14 @@ public void preprocessSwagger(Swagger swagger) { supportingTemplateFiles = JAVASCRIPT_ES6_SUPPORTING_FILES; } - for (String[] supportingTemplateFile :supportingTemplateFiles) { + for (String[] supportingTemplateFile : supportingTemplateFiles) { supportingFiles.add(new SupportingFile(supportingTemplateFile[0], "", supportingTemplateFile[1])); } } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -355,8 +340,9 @@ public String escapeReservedWord(String name) { /** * Concatenates an array of path segments into a path string. + * * @param segments The path segments to concatenate. A segment may contain either of the file separator characters '\' or '/'. - * A segment is ignored if it is null, empty or ".". + * A segment is ignored if it is null, empty or ".". * @return A path string using the correct platform-specific file separator character. */ private String createPath(String... segments) { @@ -396,6 +382,10 @@ public String modelFileFolder() { return createPath(outputFolder, sourceFolder, invokerPackage, modelPackage()); } + public String getInvokerPackage() { + return invokerPackage; + } + public void setInvokerPackage(String invokerPackage) { this.invokerPackage = invokerPackage; } @@ -491,8 +481,8 @@ public String toVarName(String name) { // sanitize name name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final" - if("_".equals(name)) { - name = "_u"; + if ("_".equals(name)) { + name = "_u"; } // if it's all uppper case, do nothing @@ -568,54 +558,39 @@ public String toApiImport(String name) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return "{String: " + getTypeDeclaration(inner) + "}"; } return super.getTypeDeclaration(p); } @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - return "'" + dp.getDefault() + "'"; + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { // TODO - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { // TODO - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return "'" + p.getDefault() + "'"; } } @@ -623,12 +598,12 @@ public String toDefaultValue(Property p) { } @Override - public String toDefaultValueWithParam(String name, Property p) { + public String toDefaultValueWithParam(String name, Schema p) { String type = normalizeType(getTypeDeclaration(p)); - if (p instanceof RefProperty) { - return " = " + type + ".constructFromObject(data['" + name + "']);"; + if (!StringUtils.isEmpty(p.get$ref())) { + return " = " + type + ".constructFromObject(data['" + p.getName() + "']);"; } else { - return " = ApiClient.convertToType(data['" + name + "'], " + type + ");"; + return " = ApiClient.convertToType(data['" + name + "'], " + type + ");"; } } @@ -697,23 +672,23 @@ public void setParameterExampleValue(CodegenParameter p) { * @return Normalized type */ public String normalizeType(String type) { - return type.replaceAll("\\b(Boolean|Integer|Number|String|Date|Blob)\\b", "'$1'"); + return type.replaceAll("\\b(Boolean|Integer|Number|String|Date|Blob)\\b", "'$1'"); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (!needToImport(type)) { return type; } } else { - type = swaggerType; + type = openAPIType; } if (null == type) { - LOGGER.error("No Type defined for Property " + p); + LOGGER.error("No Type defined for Schema " + p); } return toModelName(type); } @@ -737,64 +712,65 @@ public String toOperationId(String operationId) { return operationId; } + /* comment out below as x-codegen tag are replaced by requiredParams, optionalParams tags @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); - if (op.returnType != null) { - op.returnType = normalizeType(op.returnType); - } - - //path is an unescaped variable in the mustache template api.mustache line 82 '<&path>' - op.path = sanitizePath(op.path); - - // Set vendor-extension to be used in template: - // x-codegen-hasMoreRequired - // x-codegen-hasMoreOptional - // x-codegen-hasRequiredParams - CodegenParameter lastRequired = null; - CodegenParameter lastOptional = null; - for (CodegenParameter p : op.allParams) { - if (p.required) { - lastRequired = p; - } else { - lastOptional = p; - } - } - for (CodegenParameter p : op.allParams) { - if (p == lastRequired) { - p.vendorExtensions.put("x-codegen-hasMoreRequired", false); - } else if (p == lastOptional) { - p.vendorExtensions.put("x-codegen-hasMoreOptional", false); - } else { - p.vendorExtensions.put("x-codegen-hasMoreRequired", true); - p.vendorExtensions.put("x-codegen-hasMoreOptional", true); - } - } - op.vendorExtensions.put("x-codegen-hasRequiredParams", lastRequired != null); - - return op; + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, OpenAPI openAPI) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, openAPI); + if (op.returnType != null) { + op.returnType = normalizeType(op.returnType); + } + + //path is an unescaped variable in the mustache template api.mustache line 82 '<&path>' + op.path = sanitizePath(op.path); + + // Set vendor-extension to be used in template: + // x-codegen-hasMoreRequired + // x-codegen-hasMoreOptional + // x-codegen-hasRequiredParams + CodegenParameter lastRequired = null; + CodegenParameter lastOptional = null; + for (CodegenParameter p : op.allParams) { + if (p.required) { + lastRequired = p; + } else { + lastOptional = p; + } + } + for (CodegenParameter p : op.allParams) { + if (p == lastRequired) { + p.vendorExtensions.put("x-codegen-hasMoreRequired", false); + } else if (p == lastOptional) { + p.vendorExtensions.put("x-codegen-hasMoreOptional", false); + } else { + p.vendorExtensions.put("x-codegen-hasMoreRequired", true); + p.vendorExtensions.put("x-codegen-hasMoreOptional", true); + } + } + op.vendorExtensions.put("x-codegen-hasRequiredParams", lastRequired != null); + + return op; } + */ @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) { - final Model parentModel = allDefinitions.get(codegenModel.parentSchema); + final Schema parentModel = allDefinitions.get(codegenModel.parentSchema); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions); codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); } - if (model instanceof ArrayModel) { - ArrayModel am = (ArrayModel) model; + if (ModelUtils.isArraySchema(model)) { + ArraySchema am = (ArraySchema) model; if (am.getItems() != null) { - codegenModel.vendorExtensions.put("x-isArray", true); - codegenModel.vendorExtensions.put("x-itemType", getSwaggerType(am.getItems())); + codegenModel.getVendorExtensions().put("x-isArray", true); + codegenModel.getVendorExtensions().put("x-itemType", getSchemaType(am.getItems())); } - } else if (model instanceof ModelImpl) { - ModelImpl mm = (ModelImpl)model; - if (mm.getAdditionalProperties() != null) { - codegenModel.vendorExtensions.put("x-isMap", true); - codegenModel.vendorExtensions.put("x-itemType", getSwaggerType(mm.getAdditionalProperties())); + } else if (ModelUtils.isMapSchema(model)) { + if (model.getAdditionalProperties() != null) { + codegenModel.getVendorExtensions().put("x-isMap", true); + codegenModel.getVendorExtensions().put("x-itemType", getSchemaType((Schema) model.getAdditionalProperties())); } } @@ -805,7 +781,7 @@ private String sanitizePath(String p) { //prefer replace a ', instead of a fuLL URL encode for readability return p.replaceAll("'", "%27"); } - + private String trimBrackets(String s) { if (s != null) { int beginIdx = s.charAt(0) == '[' ? 1 : 0; @@ -819,7 +795,7 @@ private String trimBrackets(String s) { private String getModelledType(String dataType) { return "module:" + (StringUtils.isEmpty(invokerPackage) ? "" : (invokerPackage + "/")) - + (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType; + + (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType; } private String getJSDocType(CodegenModel cm, CodegenProperty cp) { @@ -894,7 +870,7 @@ public Map postProcessOperations(Map objs) { if (p.required) { argList.add(p.paramName); } else { - hasOptionalParams = true; + hasOptionalParams = true; } } if (hasOptionalParams) { @@ -973,7 +949,7 @@ public Map postProcessModels(Map objs) { @Override protected boolean needToImport(String type) { return !defaultIncludes.contains(type) - && !languageSpecificPrimitives.contains(type); + && !languageSpecificPrimitives.contains(type); } private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { @@ -1010,10 +986,10 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code } } - if(removedChildEnum) { + if (removedChildEnum) { // If we removed an entry from this model's vars, we need to ensure hasMore is updated int count = 0, numVars = codegenProperties.size(); - for(CodegenProperty codegenProperty : codegenProperties) { + for (CodegenProperty codegenProperty : codegenProperties) { count += 1; codegenProperty.hasMore = (count < numVars) ? true : false; } @@ -1027,7 +1003,7 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code private static String sanitizePackageName(String packageName) { // FIXME parameter should not be assigned. Also declare it as "final" packageName = packageName.trim(); packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_"); - if(Strings.isNullOrEmpty(packageName)) { + if (Strings.isNullOrEmpty(packageName)) { return "invalidPackageName"; } return packageName; 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 9b82d85122e2..3feaa26740f8 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 @@ -1,9 +1,22 @@ package org.openapitools.codegen.languages; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.*; -import io.swagger.models.properties.*; -import io.swagger.models.Swagger; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.oas.models.info.*; import java.util.TreeSet; import java.util.*; @@ -21,6 +34,9 @@ public JavascriptClosureAngularClientCodegen() { super(); outputFolder = "generated-code/javascript-closure-angular"; + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + supportsInheritance = false; setReservedWordsLowerCase(Arrays.asList("abstract", "continue", "for", "new", "switch", "assert", "default", "if", @@ -71,7 +87,7 @@ public JavascriptClosureAngularClientCodegen() { typeMapping.put("binary", "string"); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(USE_ES6, "use ES6 templates") @@ -82,19 +98,14 @@ public JavascriptClosureAngularClientCodegen() { public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } - if (additionalProperties.containsKey(USE_ES6)) { setUseEs6(convertPropertyToBooleanAndWriteBack(USE_ES6)); } } @Override - public void preprocessSwagger(Swagger swagger) { - super.preprocessSwagger(swagger); + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); if (useEs6) { embeddedTemplateDir = templateDir = "Javascript-Closure-Angular/es6"; @@ -200,16 +211,15 @@ public String toModelFilename(String name) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + ""; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + ""; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return "Object"; - } else if (p instanceof FileProperty) { + } else if (ModelUtils.isFileSchema(p)) { return "Object"; } String type = super.getTypeDeclaration(p); @@ -223,16 +233,16 @@ public String getTypeDeclaration(Property p) { } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); if (languageSpecificPrimitives.contains(type)) { return type; } } else - type = swaggerType; + type = schemaType; return type; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java index f1304d164d7f..3c07882ab553 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java @@ -67,7 +67,7 @@ public String getName() { } public String getHelp() { - return "Generates a kotlin client."; + return "Generates a Kotlin client."; } public void setDateLibrary(String library) { @@ -99,7 +99,6 @@ public void processOpts() { } supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java index e35a08b5ad13..708d6ed7dd79 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java @@ -2,11 +2,18 @@ import com.google.common.collect.ImmutableMap; import com.samskivert.mustache.Mustache; +import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.SupportingFile; import org.openapitools.codegen.mustache.*; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -100,7 +107,7 @@ public void setCorsFeatureEnabled(Boolean corsFeatureEnabled) { } public String getHelp() { - return "Generates a kotlin server."; + return "Generates a Kotlin server."; } public Boolean getHstsFeatureEnabled() { @@ -124,7 +131,14 @@ public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) { - this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); + this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); + } + + // set default library to "ktor" + if (StringUtils.isEmpty(library)) { + this.setLibrary("ktor"); + additionalProperties.put(CodegenConstants.LIBRARY, "ktor"); + LOGGER.info("`library` option is empty. Default to 'ktor'."); } if (additionalProperties.containsKey(Constants.AUTOMATIC_HEAD_REQUESTS)) { @@ -201,7 +215,7 @@ private void addMustacheLambdas(Map objs) { if (objs.containsKey("lambda")) { LOGGER.warn("An property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " + "You'll likely need to use a custom template, " + - "see https://github.com/swagger-api/swagger-codegen#modifying-the-client-library-format. "); + "see https://github.com/swagger-api/swagger-codegen#modifying-the-client-library-format. "); // TODO: update the URL objs.put("_lambda", lambdas); } else { objs.put("lambda", lambdas); 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 eb5135786546..8147d45f5dc1 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 @@ -1,10 +1,11 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.parameters.Parameter; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; import java.io.File; import java.util.*; @@ -47,33 +48,36 @@ public LuaClientCodegen() { embeddedTemplateDir = templateDir = "lua"; + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + setReservedWordsLowerCase( - Arrays.asList( - // data type - "nil", "string", "boolean", "number", "userdata", "thread", - "table", - - // reserved words: http://www.lua.org/manual/5.1/manual.html#2.1 - "and", "break", "do", "else", "elseif", - "end", "false", "for", "function", "if", - "in", "local", "nil", "not", "or", - "repeat", "return", "then", "true", "until", "while" - ) + Arrays.asList( + // data type + "nil", "string", "boolean", "number", "userdata", "thread", + "table", + + // reserved words: http://www.lua.org/manual/5.1/manual.html#2.1 + "and", "break", "do", "else", "elseif", + "end", "false", "for", "function", "if", + "in", "local", "nil", "not", "or", + "repeat", "return", "then", "true", "until", "while" + ) ); defaultIncludes = new HashSet( Arrays.asList( - "map", - "array") - ); + "map", + "array") + ); languageSpecificPrimitives = new HashSet( - Arrays.asList( - "nil", - "string", - "boolean", - "number") - ); + Arrays.asList( + "nil", + "string", + "boolean", + "number") + ); instantiationTypes.clear(); /*instantiationTypes.put("array", "LuaArray"); @@ -109,7 +113,7 @@ public LuaClientCodegen() { .defaultValue("swagger-client")); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Lua package version.") .defaultValue("1.0.0-1")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); } @@ -118,14 +122,6 @@ public LuaClientCodegen() { public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } @@ -155,7 +151,7 @@ public void processOpts() { //supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - supportingFiles.add(new SupportingFile("luarocks.mustache", "", luaRocksFilename)); + supportingFiles.add(new SupportingFile("luarocks.mustache", "", luaRocksFilename)); //supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.lua")); //supportingFiles.add(new SupportingFile("api_client.mustache", "", "api_client.lua")); //supportingFiles.add(new SupportingFile("api_response.mustache", "", "api_response.lua")); @@ -163,8 +159,7 @@ public void processOpts() { } @Override - public String escapeReservedWord(String name) - { + public String escapeReservedWord(String name) { // Can't start with an underscore, as our fields need to start with an // UppercaseLetter so that Lua treats them as public/visible. @@ -176,7 +171,7 @@ public String escapeReservedWord(String name) // - X_Name // ... or maybe a suffix? // - Name_ ... think this will work. - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return camelize(name) + '_'; @@ -279,7 +274,7 @@ public String toModelTestFilename(String name) { * @param parameter CodegenParameter object to be processed. */ @Override - public void postProcessParameter(CodegenParameter parameter){ + public void postProcessParameter(CodegenParameter parameter) { } @@ -319,45 +314,44 @@ public String toApiName(String name) { } @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return getTypeDeclaration(inner); - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return getTypeDeclaration(inner); } // Not using the supertype invocation, because we want to UpperCamelize // the type. - String swaggerType = getSwaggerType(p); - if (typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); + String schemaType = getSchemaType(p); + if (typeMapping.containsKey(schemaType)) { + return typeMapping.get(schemaType); } - if (typeMapping.containsValue(swaggerType)) { - return swaggerType; + if (typeMapping.containsValue(schemaType)) { + return schemaType; } - if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; + if (languageSpecificPrimitives.contains(schemaType)) { + return schemaType; } - return toModelName(swaggerType); + return toModelName(schemaType); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); if (languageSpecificPrimitives.contains(type)) return (type); } else { - type = swaggerType; + type = schemaType; } return type; } @@ -381,7 +375,7 @@ public Map postProcessOperations(Map objs) { Map objectMap = (Map) objs.get("operations"); @SuppressWarnings("unchecked") List operations = (List) objectMap.get("operation"); - for (CodegenOperation op: operations) { + for (CodegenOperation op : operations) { String[] items = op.path.split("/", -1); String luaPath = ""; @@ -439,7 +433,7 @@ public Map postProcessModels(Map objs) { @Override protected boolean needToImport(String type) { return !defaultIncludes.contains(type) - && !languageSpecificPrimitives.contains(type); + && !languageSpecificPrimitives.contains(type); } public void setPackageName(String packageName) { @@ -465,7 +459,7 @@ public String escapeUnsafeCharacters(String input) { return input.replace("]]", "] ]"); } - public Map createMapping(String key, String value){ + public Map createMapping(String key, String value) { Map customImport = new HashMap(); customImport.put(key, value); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSServerCodegen.java index 8918ceda9bf7..bcd2858df31d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSServerCodegen.java @@ -1,25 +1,25 @@ package org.openapitools.codegen.languages; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; + import org.openapitools.codegen.*; -import io.swagger.models.*; -import io.swagger.util.Yaml; +import org.openapitools.codegen.utils.*; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.info.*; +import io.swagger.v3.oas.models.PathItem.*; +import io.swagger.v3.oas.models.Paths; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; -import java.io.IOException; -import java.math.BigDecimal; +import java.net.URL; import java.util.*; import java.util.Map.Entry; import java.util.regex.Pattern; + import org.apache.commons.lang3.StringUtils; public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { @@ -28,10 +28,11 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig protected String implFolder = "service"; public static final String GOOGLE_CLOUD_FUNCTIONS = "googleCloudFunctions"; public static final String EXPORTED_NAME = "exportedName"; + public static final String SERVER_PORT = "serverPort"; protected String apiVersion = "1.0.0"; - protected int serverPort = 8080; protected String projectName = "swagger-server"; + protected String defaultServerPort = "8080"; protected boolean googleCloudFunctions; protected String exportedName; @@ -82,7 +83,6 @@ public NodeJSServerCodegen() { * are available in models, apis, and supporting files */ additionalProperties.put("apiVersion", apiVersion); - additionalProperties.put("serverPort", serverPort); additionalProperties.put("implFolder", implFolder); supportingFiles.add(new SupportingFile("writer.mustache", ("utils").replace(".", File.separator), "writer.js")); @@ -96,6 +96,8 @@ public NodeJSServerCodegen() { "When the generated code will be deployed to Google Cloud Functions, this option can be " + "used to update the name of the exported function. By default, it refers to the " + "basePath. This does not affect normal standalone nodejs server code.")); + cliOptions.add(new CliOption(SERVER_PORT, + "TCP port to listen on.")); } @Override @@ -175,7 +177,7 @@ private String implFileFolder(String output) { */ @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -285,7 +287,7 @@ public void processOpts() { } if (additionalProperties.containsKey(EXPORTED_NAME)) { - setExportedName((String)additionalProperties.get(EXPORTED_NAME)); + setExportedName((String) additionalProperties.get(EXPORTED_NAME)); } /* @@ -297,9 +299,9 @@ public void processOpts() { // "controllers", // "controller.js") // ); - supportingFiles.add(new SupportingFile("swagger.mustache", + supportingFiles.add(new SupportingFile("openapi.mustache", "api", - "swagger.yaml") + "openapi.yaml") ); if (getGoogleCloudFunctions()) { writeOptional(outputFolder, new SupportingFile("index-gcf.mustache", "", "index.js")); @@ -316,9 +318,16 @@ public void processOpts() { } @Override - public void preprocessSwagger(Swagger swagger) { - String host = swagger.getHost(); - String port = "8080"; + public void preprocessOpenAPI(OpenAPI openAPI) { + URL url = URLPathUtils.getServerURL(openAPI); + String host = URLPathUtils.LOCAL_HOST; + String port = defaultServerPort; + String basePath = null; + if (url != null) { + port = String.valueOf(url.getPort()); + host = url.getHost(); + basePath = url.getPath(); + } if (!StringUtils.isEmpty(host)) { String[] parts = host.split(":"); @@ -331,10 +340,13 @@ public void preprocessSwagger(Swagger swagger) { LOGGER.warn("'host' in the specification is empty or undefined. Default to http://localhost."); } - this.additionalProperties.put("serverPort", port); + if (additionalProperties.containsKey(SERVER_PORT)) { + port = additionalProperties.get(SERVER_PORT).toString(); + } + this.additionalProperties.put(SERVER_PORT, port); - if (swagger.getInfo() != null) { - Info info = swagger.getInfo(); + if (openAPI.getInfo() != null) { + Info info = openAPI.getInfo(); if (info.getTitle() != null) { // when info.title is defined, use it for projectName // used in package.json @@ -355,7 +367,6 @@ public void preprocessSwagger(Swagger swagger) { LOGGER.warn("Host " + host + " seems not matching with cloudfunctions.net URL."); } if (!additionalProperties.containsKey(EXPORTED_NAME)) { - String basePath = swagger.getBasePath(); if (basePath == null || basePath.equals("/")) { LOGGER.warn("Cannot find the exported name properly. Using 'openapi' as the exported name"); basePath = "/openapi"; @@ -365,23 +376,23 @@ public void preprocessSwagger(Swagger swagger) { } // need vendor extensions for x-swagger-router-controller - Map paths = swagger.getPaths(); - if(paths != null) { - for(String pathname : paths.keySet()) { - Path path = paths.get(pathname); - Map operationMap = path.getOperationMap(); - if(operationMap != null) { - for(HttpMethod method : operationMap.keySet()) { + Paths paths = openAPI.getPaths(); + if (paths != null) { + for (String pathname : paths.keySet()) { + PathItem path = paths.get(pathname); + Map operationMap = path.readOperationsMap(); + if (operationMap != null) { + for (HttpMethod method : operationMap.keySet()) { Operation operation = operationMap.get(method); String tag = "default"; - if(operation.getTags() != null && operation.getTags().size() > 0) { + if (operation.getTags() != null && operation.getTags().size() > 0) { tag = toApiName(operation.getTags().get(0)); } - if(operation.getOperationId() == null) { + if (operation.getOperationId() == null) { operation.setOperationId(getOrGenerateOperationId(operation, pathname, method.toString())); } - if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) { - operation.getVendorExtensions().put("x-swagger-router-controller", sanitizeTag(tag)); + if (operation.getExtensions().get("x-openapi-router-controller") == null) { + operation.addExtension("x-openapi-router-controller", sanitizeTag(tag)); } } } @@ -391,22 +402,8 @@ public void preprocessSwagger(Swagger swagger) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { - try { - SimpleModule module = new SimpleModule(); - module.addSerializer(Double.class, new JsonSerializer() { - @Override - public void serialize(Double val, JsonGenerator jgen, - SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeNumber(new BigDecimal(val)); - } - }); - objs.put("swagger-yaml", Yaml.mapper().registerModule(module).writeValueAsString(swagger)); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } + generateYAMLSpecFile(objs); + for (Map operations : getOperations(objs)) { @SuppressWarnings("unchecked") List ops = (List) operations.get("operation"); 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 c1e920a05592..b6c3bbdaa631 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 @@ -1,9 +1,20 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.*; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.properties.*; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import java.io.File; import java.util.Arrays; @@ -56,6 +67,9 @@ public ObjcClientCodegen() { modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + defaultIncludes.clear(); defaultIncludes.add("bool"); defaultIncludes.add("BOOL"); @@ -118,25 +132,25 @@ public ObjcClientCodegen() { // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm setReservedWordsLowerCase( - Arrays.asList( - // local variable names in API methods (endpoints) - "resourcePath", "pathParams", "queryParams", "headerParams", - "responseContentType", "requestContentType", "authSettings", - "formParams", "localVarFiles", "bodyParam", - // objc reserved words - "auto", "else", "long", "switch", - "break", "enum", "register", "typedef", - "case", "extern", "return", "union", - "char", "float", "short", "unsigned", - "const", "for", "signed", "void", - "continue", "goto", "sizeof", "volatile", - "default", "if", "id", "static", "while", - "do", "int", "struct", "_Packed", - "double", "protocol", "interface", "implementation", - "NSObject", "NSInteger", "NSNumber", "CGFloat", - "property", "nonatomic", "retain", "strong", - "weak", "unsafe_unretained", "readwrite", "readonly", - "description" + Arrays.asList( + // local variable names in API methods (endpoints) + "resourcePath", "pathParams", "queryParams", "headerParams", + "responseContentType", "requestContentType", "authSettings", + "formParams", "localVarFiles", "bodyParam", + // objc reserved words + "auto", "else", "long", "switch", + "break", "enum", "register", "typedef", + "case", "extern", "return", "union", + "char", "float", "short", "unsigned", + "const", "for", "signed", "void", + "continue", "goto", "sizeof", "volatile", + "default", "if", "id", "static", "while", + "do", "int", "struct", "_Packed", + "double", "protocol", "interface", "implementation", + "NSObject", "NSInteger", "NSNumber", "CGFloat", + "property", "nonatomic", "retain", "strong", + "weak", "unsafe_unretained", "readwrite", "readonly", + "description", "class" )); importMapping = new HashMap(); @@ -167,7 +181,7 @@ public ObjcClientCodegen() { cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") .defaultValue("https://github.com/swagger-api/swagger-codegen")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); } @@ -190,14 +204,6 @@ public String getHelp() { public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - if (additionalProperties.containsKey(POD_NAME)) { setPodName((String) additionalProperties.get(POD_NAME)); } @@ -208,7 +214,7 @@ public void processOpts() { if (additionalProperties.containsKey(CORE_DATA)) { Object coreData = additionalProperties.get(CORE_DATA); - if(((String)coreData).equalsIgnoreCase("true")) { + if (((String) coreData).equalsIgnoreCase("true")) { generateCoreData = true; } } @@ -228,7 +234,7 @@ public void processOpts() { setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); } - if(generateCoreData) { + if (generateCoreData) { modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h"); modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m"); modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h"); @@ -252,21 +258,21 @@ public void processOpts() { apiPackage = podName; supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h")); - supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); - supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); - supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); - supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); - supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); - supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); - supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); - supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); + supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); + supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); + supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); + supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); + supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); + supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); + supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); + supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); + supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h")); supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.m")); supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.h")); @@ -278,17 +284,17 @@ public void processOpts() { supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - if(generateCoreData) { + if (generateCoreData) { supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion")); - supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents")); + supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents")); } } @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { + public String toInstantiationType(Schema p) { + if (ModelUtils.isMapSchema(p)) { return instantiationTypes.get("map"); - } else if (p instanceof ArrayProperty) { + } else if (ModelUtils.isArraySchema(p)) { return instantiationTypes.get("array"); } else { return null; @@ -305,8 +311,8 @@ public String getTypeDeclaration(String name) { } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String swaggerType = super.getSchemaType(p); String type = null; if (swaggerType == null) { @@ -326,32 +332,31 @@ public String getSwaggerType(Property p) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); String innerTypeDeclaration = getTypeDeclaration(inner); if (innerTypeDeclaration.endsWith("*")) { innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); } - // In this condition, type of property p is array of primitive, + // In this condition, type of Schema p is array of primitive, // return container type with pointer, e.g. `NSArray**' if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; + return getSchemaType(p) + "<" + innerTypeDeclaration + "*>*"; } - // In this condition, type of property p is array of model, + // In this condition, type of Schema p is array of model, // return container type combine inner type with pointer, e.g. `NSArray*' else { for (String sd : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(sd)) { - return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; + if (innerTypeDeclaration.startsWith(sd)) { + return getSchemaType(p) + "<" + innerTypeDeclaration + "*>*"; } } - return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + return getSchemaType(p) + "<" + innerTypeDeclaration + ">*"; } - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); String innerTypeDeclaration = getTypeDeclaration(inner); @@ -359,17 +364,17 @@ public String getTypeDeclaration(Property p) { innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); } if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "*"; + return getSchemaType(p) + "*"; } else { for (String s : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(s)) { - return getSwaggerType(p) + "*"; + if (innerTypeDeclaration.startsWith(s)) { + return getSchemaType(p) + "*"; } } - return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + return getSchemaType(p) + "<" + innerTypeDeclaration + ">*"; } } else { - String swaggerType = getSwaggerType(p); + String swaggerType = getSchemaType(p); // In this condition, type of p is objective-c primitive type, e.g. `NSSNumber', // return type of p with pointer, e.g. `NSNumber*' if (languageSpecificPrimitives.contains(swaggerType) && @@ -398,7 +403,7 @@ public boolean isDataTypeBinary(String dataType) { public String toModelName(String type) { // model name cannot use reserved keyword if (reservedWords.contains(type)) { - LOGGER.warn(type+ " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing"); + LOGGER.warn(type + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing"); type = "model_" + type; // e.g. return => ModelReturn (after camelize) } @@ -452,12 +457,12 @@ public String toModelFilename(String name) { } @Override - protected void setNonArrayMapProperty(CodegenProperty property, String type) { - super.setNonArrayMapProperty(property, type); + protected void setNonArrayMapProperty(CodegenProperty schema, String type) { + super.setNonArrayMapProperty(schema, type); if ("NSDictionary".equals(type)) { - property.setter = "initWithDictionary"; + schema.setter = "initWithDictionary"; } else { - property.setter = "initWithValues"; + schema.setter = "initWithValues"; } } @@ -488,12 +493,12 @@ public String toApiDocFilename(String name) { @Override public String apiFileFolder() { - return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); + return (outputFolder + "/" + apiPackage() + "/" + apiFilesPath).replace("/", File.separator); } @Override public String modelFileFolder() { - return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); + return (outputFolder + "/" + modelPackage() + "/" + modelFilesPath).replace("/", File.separator); } public String coreFileFolder() { @@ -553,7 +558,7 @@ public String toParamName(String name) { */ @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -624,55 +629,41 @@ public Map postProcessOperations(Map objs) { } @Override - public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ - super.postProcessModelProperty(model,property); - property.vendorExtensions.put("x-uppercaseName", camelize(property.name)); + public void postProcessModelProperty(CodegenModel model, CodegenProperty schema) { + super.postProcessModelProperty(model, schema); + schema.vendorExtensions.put("x-uppercaseName", camelize(schema.name)); } /** - * Return the default value of the property + * Return the default value of the schema * - * @param p Swagger property object - * @return string presentation of the default value of the property + * @param p Swagger schema object + * @return string presentation of the default value of the schema */ @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - return "@\"" + dp.getDefault() + "\""; - } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getDefault() != null) { - if (dp.getDefault().toString().equalsIgnoreCase("false")) - return "@(NO)"; - else - return "@(YES)"; - } - } else if (p instanceof DateProperty) { + public String toDefaultValue(Schema p) { + if (ModelUtils.isDateSchema(p)) { // TODO - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { // TODO - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return "@" + dp.getDefault().toString(); + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + return "@" + p.getDefault().toString(); } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return "@" + dp.getDefault().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return "@" + p.getDefault().toString(); } - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return "@" + dp.getDefault().toString(); + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return "@\"" + (String) p.getDefault() + "\""; } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return "@" + dp.getDefault().toString(); + } else if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + if (p.getDefault().toString().equalsIgnoreCase("false")) + return "@(NO)"; + else + return "@(YES)"; } } @@ -731,7 +722,7 @@ public void setParameterExampleValue(CodegenParameter p) { example = "@\"" + escapeText(example) + "\""; } else if ("NSData".equalsIgnoreCase(type)) { example = "1234"; - } else if (!languageSpecificPrimitives.contains(type)) { + } else if (type != null && !languageSpecificPrimitives.contains(type)) { // type is a model class, e.g. User type = type.replace("*", ""); // e.g. [[SWGPet alloc] init diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwaggerGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java similarity index 53% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwaggerGenerator.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java index 367ced74e7ef..9fa09c51afef 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwaggerGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java @@ -6,21 +6,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.SupportingFile; -import io.swagger.models.Swagger; -import io.swagger.util.Json; +import org.openapitools.codegen.*; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.core.util.Json; -public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig { +public class OpenAPIGenerator extends DefaultCodegen implements CodegenConfig { - private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerGenerator.class); + private static final Logger LOGGER = LoggerFactory.getLogger(OpenAPIGenerator.class); - public SwaggerGenerator() { + public OpenAPIGenerator() { super(); - embeddedTemplateDir = templateDir = "swagger"; - outputFolder = "generated-code/swagger"; + embeddedTemplateDir = templateDir = "openapi"; + outputFolder = "generated-code/openapi"; supportingFiles.add(new SupportingFile("README.md", "", "README.md")); } @@ -32,36 +29,36 @@ public CodegenType getTag() { @Override public String getName() { - return "swagger"; + return "openapi"; } @Override public String getHelp() { - return "Creates a static swagger.json file."; + return "Creates a static openapi.json file (OpenAPI spec v3.0)."; } @Override - public void processSwagger(Swagger swagger) { - String swaggerString = Json.pretty(swagger); + public void processOpenAPI(OpenAPI openAPI) { + String swaggerString = Json.pretty(openAPI); try { - String outputFile = outputFolder + File.separator + "swagger.json"; + String outputFile = outputFolder + File.separator + "openapi.json"; FileUtils.writeStringToFile(new File(outputFile), swaggerString); - LOGGER.debug("wrote file to " + outputFile); + LOGGER.info("wrote file to " + outputFile); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } @Override - public String escapeQuotationMark(String input) { + public String escapeQuotationMark(String input) { // just return the original string return input; - } + } @Override - public String escapeUnsafeCharacters(String input) { + public String escapeUnsafeCharacters(String input) { // just return the original string return input; - } + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwaggerYamlGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIYamlGenerator.java similarity index 53% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwaggerYamlGenerator.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIYamlGenerator.java index b341f4ea134d..9533a8b263f0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwaggerYamlGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIYamlGenerator.java @@ -1,29 +1,28 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.Swagger; -import io.swagger.util.Yaml; -import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Map; import java.io.File; -public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig { +public class OpenAPIYamlGenerator extends DefaultCodegen implements CodegenConfig { public static final String OUTPUT_NAME = "outputFile"; - private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerYamlGenerator.class); + private static final Logger LOGGER = LoggerFactory.getLogger(OpenAPIYamlGenerator.class); - protected String outputFile = "swagger.yaml"; + protected String outputFile = "openapi.yaml"; - public SwaggerYamlGenerator() { + public OpenAPIYamlGenerator() { super(); - embeddedTemplateDir = templateDir = "swagger"; - outputFolder = "generated-code/swagger"; - + embeddedTemplateDir = templateDir = "openapi-yaml"; + outputFolder = "generated-code/openapi-yaml"; cliOptions.add(new CliOption(OUTPUT_NAME, "output filename")); - supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + supportingFiles.add(new SupportingFile("openapi.mustache", + "openapi", + "openapi.yaml")); } @Override @@ -33,35 +32,30 @@ public CodegenType getTag() { @Override public String getName() { - return "swagger-yaml"; + return "openapi-yaml"; } @Override public String getHelp() { - return "Creates a static swagger.yaml file."; + return "Creates a static openapi.yaml file (OpenAPI spec v3)."; } @Override public void processOpts() { super.processOpts(); - if(additionalProperties.containsKey(OUTPUT_NAME)) { + if (additionalProperties.containsKey(OUTPUT_NAME)) { this.outputFile = additionalProperties.get(OUTPUT_NAME).toString(); } } @Override - public void processSwagger(Swagger swagger) { - try { - String swaggerString = Yaml.mapper().writeValueAsString(swagger); - String outputFile = outputFolder + File.separator + this.outputFile; - FileUtils.writeStringToFile(new File(outputFile), swaggerString); - LOGGER.debug("wrote file to " + outputFile); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - } + public Map postProcessSupportingFileData(Map objs) { + generateYAMLSpecFile(objs); + return super.postProcessSupportingFileData(objs); } + @Override public String escapeQuotationMark(String input) { // just return the original string @@ -72,6 +66,6 @@ public String escapeQuotationMark(String input) { public String escapeUnsafeCharacters(String input) { // just return the original string return input; - } + } } 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 1a753badea80..62dd16082627 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 @@ -7,20 +7,11 @@ import org.openapitools.codegen.SupportingFile; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.CliOption; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.BinaryProperty; -import io.swagger.models.properties.ByteArrayProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DateProperty; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import java.io.File; import java.util.Arrays; @@ -111,6 +102,13 @@ public PerlClientCodegen() { .ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); + + // option to change the order of form/body parameter + cliOptions.add(CliOption.newBoolean( + CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, + CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS_DESC) + .defaultValue(Boolean.FALSE.toString())); + } @@ -135,14 +133,6 @@ public void processOpts() { additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiClient.pm")); supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Configuration.pm")); supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiFactory.pm")); @@ -171,7 +161,7 @@ public String getHelp() { @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -208,22 +198,21 @@ public String modelDocFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String swaggerType = super.getSchemaType(p); String type = null; if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); @@ -240,40 +229,26 @@ public String getSwaggerType(Property p) { } @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - return "'" + dp.getDefault() + "'"; - } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { // TODO - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { // TODO - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return "'" + p.getDefault() + "'"; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java index 50dd29ece7d5..692bc9f55c7f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java @@ -9,7 +9,7 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.*; +import org.openapitools.codegen.utils.ModelUtils; import java.io.File; import java.util.Arrays; @@ -23,6 +23,10 @@ import org.apache.commons.lang3.StringUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,7 +49,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String docsBasePath = "docs"; protected String apiDirName = "Api"; protected String modelDirName = "Model"; - protected String variableNamingConvention= "snake_case"; + protected String variableNamingConvention = "snake_case"; protected String apiDocPath = docsBasePath + "/" + apiDirName; protected String modelDocPath = docsBasePath + "/" + modelDirName; @@ -69,14 +73,17 @@ public PhpClientCodegen() { modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + setReservedWordsLowerCase( Arrays.asList( - // local variables used in api methods (endpoints) - "resourcePath", "httpBody", "queryParams", "headerParams", - "formParams", "_header_accept", "_tempBody", + // local variables used in api methods (endpoints) + "resourcePath", "httpBody", "queryParams", "headerParams", + "formParams", "_header_accept", "_tempBody", - // PHP reserved words - "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") + // PHP reserved words + "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") ); // ref: http://php.net/manual/en/language.types.intro.php @@ -102,7 +109,7 @@ public PhpClientCodegen() { // provide primitives to mustache template - List sortedLanguageSpecificPrimitives= new ArrayList(languageSpecificPrimitives); + List sortedLanguageSpecificPrimitives = new ArrayList(languageSpecificPrimitives); Collections.sort(sortedLanguageSpecificPrimitives); String primitives = "'" + StringUtils.join(sortedLanguageSpecificPrimitives, "', '") + "'"; additionalProperties.put("primitives", primitives); @@ -125,7 +132,7 @@ public PhpClientCodegen() { typeMapping.put("array", "array"); typeMapping.put("list", "array"); typeMapping.put("object", "object"); - typeMapping.put("binary", "string"); + typeMapping.put("binary", "\\SplFileObject"); typeMapping.put("ByteArray", "string"); typeMapping.put("UUID", "string"); @@ -141,7 +148,7 @@ public PhpClientCodegen() { cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release")); cliOptions.add(new CliOption(CodegenConstants.GIT_REPO_ID, CodegenConstants.GIT_REPO_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.ALLOW_UNICODE_IDENTIFIERS_DESC) .defaultValue(Boolean.TRUE.toString())); } @@ -179,7 +186,7 @@ public String toSrcPath(String packageName, String basePath) { // Trim prefix file separators from package path .replaceAll(regFirstPathSeparator, "")) // Trim trailing file separators from the overall path - .replaceAll(regLastPathSeparator+ "$", ""); + .replaceAll(regLastPathSeparator + "$", ""); } @Override @@ -210,14 +217,6 @@ public String getHelp() { public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - if (additionalProperties.containsKey(PACKAGE_PATH)) { this.setPackagePath((String) additionalProperties.get(PACKAGE_PATH)); } else { @@ -316,7 +315,7 @@ public void processOpts() { @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -363,16 +362,15 @@ public String toApiDocFilename(String name) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return getTypeDeclaration(inner) + "[]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; - } else if (p instanceof RefProperty) { + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } else if (StringUtils.isNotBlank(p.get$ref())) { String type = super.getTypeDeclaration(p); return (!languageSpecificPrimitives.contains(type)) ? "\\" + modelPackage + "\\" + type : type; @@ -389,18 +387,18 @@ public String getTypeDeclaration(String name) { } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); if (languageSpecificPrimitives.contains(type)) { return type; } else if (instantiationTypes.containsKey(type)) { return type; } } else { - type = swaggerType; + type = schemaType; } if (type == null) { return null; @@ -408,6 +406,10 @@ public String getSwaggerType(Property p) { return toModelName(type); } + public String getInvokerPackage() { + return invokerPackage; + } + public void setInvokerPackage(String invokerPackage) { this.invokerPackage = invokerPackage; } @@ -442,13 +444,13 @@ public String toVarName(String name) { name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. if ("camelCase".equals(variableNamingConvention)) { - // return the name in camelCase style - // phone_number => phoneNumber - name = camelize(name, true); + // return the name in camelCase style + // phone_number => phoneNumber + name = camelize(name, true); } else { // default to snake case - // return the name in underscore style - // PhoneNumber => phone_number - name = underscore(name); + // return the name in underscore style + // PhoneNumber => phone_number + name = underscore(name); } // parameter name starting with number won't compile @@ -536,44 +538,30 @@ public String toOperationId(String operationId) { /** * Return the default value of the property * - * @param p Swagger property object + * @param p property schema * @return string presentation of the default value of the property */ @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - return "'" + dp.getDefault() + "'"; + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { // TODO - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { // TODO - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return "'" + p.getDefault() + "'"; } } @@ -595,7 +583,7 @@ public void setParameterExampleValue(CodegenParameter p) { type = p.dataType; } - if ("String".equalsIgnoreCase(type)) { + if ("String".equalsIgnoreCase(type) || p.isString) { if (example == null) { example = p.paramName + "_example"; } @@ -612,9 +600,9 @@ public void setParameterExampleValue(CodegenParameter p) { if (example == null) { example = "True"; } - } else if ("\\SplFileObject".equalsIgnoreCase(type)) { + } else if ("\\SplFileObject".equalsIgnoreCase(type) || p.isFile) { if (example == null) { - example = "/path/to/file"; + example = "/path/to/file.txt"; } example = "\"" + escapeText(example) + "\""; } else if ("\\Date".equalsIgnoreCase(type)) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LumenServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLumenServerCodegen.java similarity index 86% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LumenServerCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLumenServerCodegen.java index ce6348ccd4d9..17084db375a4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LumenServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLumenServerCodegen.java @@ -10,16 +10,15 @@ import java.util.Map; import java.util.TreeMap; -public class LumenServerCodegen extends AbstractPhpCodegen -{ - @SuppressWarnings("hiding") +public class PhpLumenServerCodegen extends AbstractPhpCodegen { + @SuppressWarnings("hiding") protected String apiVersion = "1.0.0"; - + /** * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see org.openapitools.codegen.CodegenType + * + * @return the CodegenType for this generator + * @see org.openapitools.codegen.CodegenType */ public CodegenType getTag() { return CodegenType.SERVER; @@ -28,24 +27,24 @@ public CodegenType getTag() { /** * Configures a friendly name for the generator. This will be used by the generator * to select the library with the -l flag. - * + * * @return the friendly name for the generator */ public String getName() { - return "lumen"; + return "php-lumen"; } /** * Returns human-friendly help for the generator. Provide the consumer with help * tips, parameters here - * + * * @return A string value for the help message */ public String getHelp() { - return "Generates a LumenServerCodegen server library."; + return "Generates a PHP Lumen server library."; } - public LumenServerCodegen() { + public PhpLumenServerCodegen() { super(); embeddedTemplateDir = templateDir = "lumen"; @@ -88,13 +87,13 @@ public LumenServerCodegen() { supportingFiles.add(new SupportingFile("app.php", packagePath + File.separator + srcBasePath + File.separator + "bootstrap", "app.php")); supportingFiles.add(new SupportingFile("index.php", packagePath + File.separator + srcBasePath + File.separator + "public", "index.php")); supportingFiles.add(new SupportingFile("User.php", packagePath + File.separator + srcBasePath + File.separator + "app", "User.php")); - supportingFiles.add(new SupportingFile("Kernel.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Console", "Kernel.php")); - supportingFiles.add(new SupportingFile("Handler.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Exceptions", "Handler.php")); - supportingFiles.add(new SupportingFile("routes.mustache", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http", "routes.php")); - - supportingFiles.add(new SupportingFile("Controller.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "Controller.php")); - supportingFiles.add(new SupportingFile("Authenticate.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "Authenticate.php")); - + supportingFiles.add(new SupportingFile("Kernel.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Console", "Kernel.php")); + supportingFiles.add(new SupportingFile("Handler.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Exceptions", "Handler.php")); + supportingFiles.add(new SupportingFile("routes.mustache", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http", "routes.php")); + + supportingFiles.add(new SupportingFile("Controller.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "Controller.php")); + supportingFiles.add(new SupportingFile("Authenticate.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "Authenticate.php")); + } // override with any special post-processing @@ -113,7 +112,7 @@ public Map postProcessOperations(Map objs) { throw new IllegalArgumentException("'.' (dot) is not supported by PHP Lumen. Please refer to https://github.com/swagger-api/swagger-codegen/issues/6897 for more info."); } } - + // sort the endpoints in ascending to avoid the route priority issure. // https://github.com/swagger-api/swagger-codegen/issues/2643 Collections.sort(operations, new Comparator() { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SilexServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java similarity index 87% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SilexServerCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java index d39116875ea3..b5c39e3e96c0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SilexServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java @@ -6,9 +6,11 @@ import org.openapitools.codegen.CodegenOperation; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import java.io.File; import java.util.Arrays; @@ -19,13 +21,13 @@ import org.apache.commons.lang3.StringUtils; -public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig { +public class PhpSilexServerCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage; protected String groupId = "io.swagger"; protected String artifactId = "swagger-server"; protected String artifactVersion = "1.0.0"; - public SilexServerCodegen() { + public PhpSilexServerCodegen() { super(); invokerPackage = camelize("SwaggerServer"); @@ -102,7 +104,9 @@ public CodegenType getTag() { } @Override - public String getName() { + public String getName() + + { return "php-silex"; } @@ -112,13 +116,13 @@ public String getHelp() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; } - + @Override public String apiFileFolder() { return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar); @@ -130,22 +134,21 @@ public String modelFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String swaggerType = super.getSchemaType(p); String type = null; if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); @@ -164,7 +167,7 @@ public String getSwaggerType(Property p) { } @Override - public String toDefaultValue(Property p) { + public String toDefaultValue(Schema p) { return "null"; } @@ -232,7 +235,7 @@ public Map postProcessOperations(Map objs) { 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] = "{" + camelize(items[i].substring(1, items[i].length() - 1), true) + "}"; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SlimFrameworkServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java similarity index 82% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SlimFrameworkServerCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java index 86a52b3bd000..fd76a61eee2e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SlimFrameworkServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java @@ -1,14 +1,17 @@ package org.openapitools.codegen.languages; +import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.core.util.Yaml; import java.io.File; import java.util.Arrays; @@ -16,7 +19,7 @@ import java.util.HashSet; import java.util.regex.Matcher; -public class SlimFrameworkServerCodegen extends DefaultCodegen implements CodegenConfig { +public class PhpSlimServerCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage; protected String srcBasePath = "lib"; protected String groupId = "io.swagger"; @@ -27,7 +30,7 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege private String variableNamingConvention = "camelCase"; - public SlimFrameworkServerCodegen() { + public PhpSlimServerCodegen() { super(); // clear import mapping (from default generator) as slim does not use it @@ -109,17 +112,17 @@ public CodegenType getTag() { @Override public String getName() { - return "slim"; + return "php-slim"; } @Override public String getHelp() { - return "Generates a Slim Framework server library."; + return "Generates a PHP Slim Framework server library."; } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -136,16 +139,15 @@ public String modelFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return getTypeDeclaration(inner) + "[]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; - } else if (p instanceof RefProperty) { + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } else if (!StringUtils.isEmpty(p.get$ref())) { String type = super.getTypeDeclaration(p); return (!languageSpecificPrimitives.contains(type)) ? "\\" + modelPackage + "\\" + type : type; @@ -154,18 +156,18 @@ public String getTypeDeclaration(Property p) { } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) { return type; } else if (instantiationTypes.containsKey(type)) { return type; } } else { - type = swaggerType; + type = openAPIType; } if (type == null) { return null; @@ -182,7 +184,7 @@ public String getTypeDeclaration(String name) { } @Override - public String toDefaultValue(Property p) { + public String toDefaultValue(Schema p) { return "null"; } @@ -197,11 +199,11 @@ public String toVarName(String name) { if ("camelCase".equals(variableNamingConvention)) { // return the name in camelCase style // phone_number => phoneNumber - name = camelize(name, true); + name = camelize(name, true); } else { // default to snake case // return the name in underscore style // PhoneNumber => phone_number - name = underscore(name); + name = underscore(name); } // parameter name starting with number won't compile @@ -258,12 +260,12 @@ public String toPackagePath(String packageName, String basePath) { } return (getPackagePath() + File.separatorChar + basePath - // Replace period, backslash, forward slash with file separator in package name - + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) - // Trim prefix file separators from package path - .replaceAll(regFirstPathSeparator, "")) - // Trim trailing file separators from the overall path - .replaceAll(regLastPathSeparator+ "$", ""); + // Replace period, backslash, forward slash with file separator in package name + + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) + // Trim prefix file separators from package path + .replaceAll(regFirstPathSeparator, "")) + // Trim trailing file separators from the overall path + .replaceAll(regLastPathSeparator + "$", ""); } public String getPackagePath() { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SymfonyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java similarity index 87% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SymfonyServerCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java index eb559a79dcee..edff9886996c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SymfonyServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java @@ -1,10 +1,15 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.core.util.Yaml; + import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -12,9 +17,9 @@ import java.io.File; import java.util.*; -public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenConfig { +public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements CodegenConfig { @SuppressWarnings("hiding") - static Logger LOGGER = LoggerFactory.getLogger(SymfonyServerCodegen.class); + static Logger LOGGER = LoggerFactory.getLogger(PhpSymfonyServerCodegen.class); public static final String BUNDLE_NAME = "bundleName"; public static final String COMPOSER_VENDOR_NAME = "composerVendorName"; @@ -58,7 +63,7 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC SYMFONY_EXCEPTIONS.put("503", "Symfony\\Component\\HttpKernel\\Exception\\ServiceUnavailableHttpException"); } - public SymfonyServerCodegen() { + public PhpSymfonyServerCodegen() { super(); // clear import mapping (from default generator) as php does not use it @@ -81,45 +86,48 @@ public SymfonyServerCodegen() { apiTestTemplateFiles.put("testing/api_test.mustache", ".php"); embeddedTemplateDir = templateDir = "php-symfony"; + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + setReservedWordsLowerCase( - Arrays.asList( - // local variables used in api methods (endpoints) - "resourcePath", "httpBody", "queryParams", "headerParams", - "formParams", "_header_accept", "_tempBody", - - // PHP reserved words - "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor" - ) + Arrays.asList( + // local variables used in api methods (endpoints) + "resourcePath", "httpBody", "queryParams", "headerParams", + "formParams", "_header_accept", "_tempBody", + + // PHP reserved words + "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor" + ) ); // ref: http://php.net/manual/en/language.types.intro.php languageSpecificPrimitives = new HashSet( - Arrays.asList( - "bool", - "int", - "double", - "float", - "string", - "object", - "mixed", - "number", - "void", - "byte", - "array" - ) + Arrays.asList( + "bool", + "int", + "double", + "float", + "string", + "object", + "mixed", + "number", + "void", + "byte", + "array" + ) ); defaultIncludes = new HashSet( - Arrays.asList( - "\\DateTime", - "UploadedFile" - ) + Arrays.asList( + "\\DateTime", + "UploadedFile" + ) ); variableNamingConvention = "camelCase"; // provide primitives to mustache template - List sortedLanguageSpecificPrimitives= new ArrayList(languageSpecificPrimitives); + List sortedLanguageSpecificPrimitives = new ArrayList(languageSpecificPrimitives); Collections.sort(sortedLanguageSpecificPrimitives); String primitives = "'" + StringUtils.join(sortedLanguageSpecificPrimitives, "', '") + "'"; additionalProperties.put("primitives", primitives); @@ -148,7 +156,7 @@ public SymfonyServerCodegen() { cliOptions.add(new CliOption(COMPOSER_VENDOR_NAME, "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets. IMPORTANT NOTE (2016/03): composerVendorName will be deprecated and replaced by gitUserId in the next swagger-codegen release")); cliOptions.add(new CliOption(BUNDLE_NAME, "The name of the Symfony bundle. The template uses {{bundleName}}")); cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(PHP_LEGACY_SUPPORT, "Should the generated code be compatible with PHP 5.x?").defaultValue(Boolean.TRUE.toString())); } @@ -209,14 +217,6 @@ public String apiFilename(String templateName, String tag) { public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - if (additionalProperties.containsKey(BUNDLE_NAME)) { this.setBundleName((String) additionalProperties.get(BUNDLE_NAME)); } else { @@ -298,7 +298,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md")); - + supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml")); supportingFiles.add(new SupportingFile(".php_cs", getPackagePath(), ".php_cs")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), "git_push.sh")); @@ -307,19 +307,19 @@ public void processOpts() { // ref: http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration if (phpLegacySupport) { typeHintable = new HashSet( - Arrays.asList( - "array" - ) + Arrays.asList( + "array" + ) ); } else { typeHintable = new HashSet( - Arrays.asList( - "array", - "bool", - "float", - "int", - "string" - ) + Arrays.asList( + "array", + "bool", + "float", + "int", + "string" + ) ); } } @@ -347,13 +347,13 @@ public Map postProcessOperations(Map objs) { } if (param.isContainer) { - param.vendorExtensions.put("x-parameterType", getTypeHint(param.dataType+"[]")); + param.vendorExtensions.put("x-parameterType", getTypeHint(param.dataType + "[]")); } // Create a variable to display the correct data type in comments for interfaces param.vendorExtensions.put("x-commentType", param.dataType); if (param.isContainer) { - param.vendorExtensions.put("x-commentType", param.dataType+"[]"); + param.vendorExtensions.put("x-commentType", param.dataType + "[]"); } // Quote default values for strings @@ -361,7 +361,7 @@ public Map postProcessOperations(Map objs) { // in DefaultCodegen fromParameter with no real possibility to override // the functionality. Thus we are handling quoting of string values here if (param.dataType.equals("string") && param.defaultValue != null && !param.defaultValue.isEmpty()) { - param.defaultValue = "'"+param.defaultValue+"'"; + param.defaultValue = "'" + param.defaultValue + "'"; } } @@ -369,7 +369,7 @@ public Map postProcessOperations(Map objs) { if (op.returnType != null) { op.vendorExtensions.put("x-commentType", op.returnType); if (!op.returnTypeIsPrimitive) { - op.vendorExtensions.put("x-commentType", op.returnType+"[]"); + op.vendorExtensions.put("x-commentType", op.returnType + "[]"); } } else { op.vendorExtensions.put("x-commentType", "void"); @@ -407,7 +407,7 @@ public Map postProcessModels(Map objs) { // Create a variable to display the correct data type in comments for models var.vendorExtensions.put("x-commentType", var.datatype); if (var.isContainer) { - var.vendorExtensions.put("x-commentType", var.datatype+"[]"); + var.vendorExtensions.put("x-commentType", var.datatype + "[]"); } if (var.isBoolean) { @@ -421,7 +421,7 @@ public Map postProcessModels(Map objs) { @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -458,20 +458,19 @@ public void setInvokerPackage(String invokerPackage) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return getTypeDeclaration(inner); } - if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return getTypeDeclaration(inner); } - if (p instanceof RefProperty) { + if (!StringUtils.isEmpty(p.get$ref())) { return getTypeDeclaration(getPropertyTypeDeclaration(p)); } @@ -481,15 +480,15 @@ public String getTypeDeclaration(Property p) { /** * Output the type declaration of the property * - * @param p Swagger Property object + * @param p Swagger Schema object * @return a string presentation of the property type */ - public String getPropertyTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - if (typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); + public String getPropertyTypeDeclaration(Schema p) { + String openAPIType = getSchemaType(p); + if (typeMapping.containsKey(openAPIType)) { + return typeMapping.get(openAPIType); } - return swaggerType; + return openAPIType; } @Override @@ -579,7 +578,7 @@ protected String getTypeHint(String type) { // This parameter is an instance of a model return extractSimpleName(type); } - + // PHP does not support type hinting for this parameter data type return ""; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ZendExpressivePathHandlerServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpZendExpressivePathHandlerServerCodegen.java similarity index 62% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ZendExpressivePathHandlerServerCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpZendExpressivePathHandlerServerCodegen.java index fdefb00d2c2d..05b01e5d964e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ZendExpressivePathHandlerServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpZendExpressivePathHandlerServerCodegen.java @@ -1,10 +1,15 @@ package org.openapitools.codegen.languages; +import io.swagger.v3.oas.models.PathItem; import org.openapitools.codegen.*; -import io.swagger.models.*; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.parameters.QueryParameter; -import io.swagger.models.properties.*; + +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.core.util.Yaml; +import io.swagger.v3.oas.models.parameters.*; +import org.openapitools.codegen.utils.ModelUtils; import java.io.File; @@ -13,7 +18,7 @@ import java.util.List; import java.util.Map; -public class ZendExpressivePathHandlerServerCodegen extends AbstractPhpCodegen { +public class PhpZendExpressivePathHandlerServerCodegen extends AbstractPhpCodegen { public static final String VEN_FROM_QUERY = "internal.ze-ph.fromQuery"; public static final String VEN_COLLECTION_FORMAT = "internal.ze-ph.collectionFormat"; @@ -27,7 +32,7 @@ public CodegenType getTag() { @Override public String getName() { - return "ze-ph"; + return "php-ze-ph"; } @Override @@ -35,7 +40,7 @@ public String getHelp() { return "Generates PHP server stub using Zend Expressive ( https://zendframework.github.io/zend-expressive ) and Path Handler ( https://github.com/Articus/PathHandler )."; } - public ZendExpressivePathHandlerServerCodegen() { + public PhpZendExpressivePathHandlerServerCodegen() { super(); //no point to use double - http://php.net/manual/en/language.types.float.php , especially because of PHP 7+ float type declaration typeMapping.put("double", "float"); @@ -133,111 +138,119 @@ public String toApiName(String name) { /** * Generate additional model definitions from query parameters * - * @param swagger + * @param openAPI OpenAPI object */ @Override - public void preprocessSwagger(Swagger swagger) { - super.preprocessSwagger(swagger); - for (String pathKey : swagger.getPaths().keySet()) - { - Path path = swagger.getPath(pathKey); - Map operations = path.getOperationMap(); - for (HttpMethod method : operations.keySet()) - { - Operation operation = operations.get(method); - Map properties = new HashMap<>(); - for (Parameter parameter : operation.getParameters()) - { - Property property = convertParameterToProperty(parameter); - if (property != null) - { - properties.put(property.getName(), property); + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); + + Map paths = openAPI.getPaths(); + if (paths != null) { + for (String pathname : paths.keySet()) { + PathItem path = paths.get(pathname); + Map operationMap = path.readOperationsMap(); + if (operationMap != null) { + for (HttpMethod method : operationMap.keySet()) { + Operation operation = operationMap.get(method); + Map schemas = new HashMap<>(); + if (operation == null || operation.getParameters() == null) { + continue; + } + + for (Parameter parameter : operation.getParameters()) { + Schema schema = convertParameterToSchema(parameter); + if (schema != null) { + schemas.put(schema.getName(), schema); + } + } + + if (!schemas.isEmpty()) { + Schema model = new Schema(); + String operationId = getOrGenerateOperationId(operation, pathname, method.name()); + model.setDescription("Query parameters for " + operationId); + model.setProperties(schemas); + model.addExtension(VEN_FROM_QUERY, Boolean.TRUE); + String definitionName = generateUniqueDefinitionName(operationId + "QueryData", openAPI); + openAPI.getComponents().addSchemas(definitionName, model); + String definitionModel = "\\" + modelPackage + "\\" + toModelName(definitionName); + operation.addExtension(VEN_QUERY_DATA_TYPE, definitionModel); + operation.addExtension(VEN_HAS_QUERY_DATA, Boolean.TRUE); + } } } - if (!properties.isEmpty()) - { - Model model = new ModelImpl(); - String operationId = getOrGenerateOperationId(operation, pathKey, method.name()); - model.setDescription("Query parameters for " + operationId); - model.setProperties(properties); - model.getVendorExtensions().put(VEN_FROM_QUERY, Boolean.TRUE); - String definitionName = generateUniqueDefinitionName(operationId + "QueryData", swagger); - swagger.addDefinition(definitionName, model); - String definitionModel = "\\" + modelPackage + "\\" + toModelName(definitionName); - operation.getVendorExtensions().put(VEN_QUERY_DATA_TYPE, definitionModel); - operation.getVendorExtensions().put(VEN_HAS_QUERY_DATA, Boolean.TRUE); - } } } } - protected Property convertParameterToProperty(Parameter parameter) { - Property property = null; - if (parameter instanceof QueryParameter) - { + protected Schema convertParameterToSchema(Parameter parameter) { + Schema property = null; + if (parameter instanceof QueryParameter) { QueryParameter queryParameter = (QueryParameter) parameter; - switch (queryParameter.getType()) - { - case "string": - StringProperty stringProperty = new StringProperty(); - stringProperty.setMinLength(queryParameter.getMinLength()); - stringProperty.setMaxLength(queryParameter.getMaxLength()); - stringProperty.setPattern(queryParameter.getPattern()); - stringProperty.setEnum(queryParameter.getEnum()); - property = stringProperty; - break; - case "integer": - IntegerProperty integerProperty = new IntegerProperty(); - integerProperty.setMinimum(queryParameter.getMinimum()); - integerProperty.setMaximum(queryParameter.getMaximum()); - property = integerProperty; - break; - case "number": - FloatProperty floatProperty = new FloatProperty(); - floatProperty.setMinimum(queryParameter.getMinimum()); - floatProperty.setMaximum(queryParameter.getMaximum()); - property = floatProperty; - break; - case "boolean": - property = new BooleanProperty(); - break; - case "array": - ArrayProperty arrayProperty = new ArrayProperty(); - arrayProperty.setMinItems(queryParameter.getMinItems()); - arrayProperty.setMaxItems(queryParameter.getMaxItems()); - arrayProperty.setItems(queryParameter.getItems()); - String collectionFormat = queryParameter.getCollectionFormat(); - if (collectionFormat == null) { - collectionFormat = "csv"; - } - arrayProperty.getVendorExtensions().put(VEN_COLLECTION_FORMAT, collectionFormat); - property = arrayProperty; - break; - case "date": - property = new DateProperty(); - break; - case "date-time": - property = new DateTimeProperty(); - break; + // array + if (ModelUtils.isArraySchema(queryParameter.getSchema())) { + Schema inner = ((ArraySchema) queryParameter.getSchema()).getItems(); + ArraySchema arraySchema = new ArraySchema(); + arraySchema.setMinItems(queryParameter.getSchema().getMinItems()); + arraySchema.setMaxItems(queryParameter.getSchema().getMaxItems()); + arraySchema.setItems(inner); + String collectionFormat = getCollectionFormat(queryParameter); + if (collectionFormat == null) { + collectionFormat = "csv"; + } + arraySchema.addExtension(VEN_COLLECTION_FORMAT, collectionFormat); + property = arraySchema; + } else { // non-array e.g. string, integer + switch (queryParameter.getSchema().getType()) { + case "string": + StringSchema stringSchema = new StringSchema(); + stringSchema.setMinLength(queryParameter.getSchema().getMinLength()); + stringSchema.setMaxLength(queryParameter.getSchema().getMaxLength()); + stringSchema.setPattern(queryParameter.getSchema().getPattern()); + stringSchema.setEnum(queryParameter.getSchema().getEnum()); + property = stringSchema; + break; + case "integer": + IntegerSchema integerSchema = new IntegerSchema(); + integerSchema.setMinimum(queryParameter.getSchema().getMinimum()); + integerSchema.setMaximum(queryParameter.getSchema().getMaximum()); + property = integerSchema; + break; + case "number": + NumberSchema floatSchema = new NumberSchema(); + floatSchema.setMinimum(queryParameter.getSchema().getMinimum()); + floatSchema.setMaximum(queryParameter.getSchema().getMaximum()); + property = floatSchema; + break; + case "boolean": + property = new BooleanSchema(); + break; + case "date": + property = new DateSchema(); + break; + case "date-time": + property = new DateTimeSchema(); + break; + } } - if (property != null) - { + if (property != null) { property.setName(queryParameter.getName()); property.setDescription(queryParameter.getDescription()); - property.setRequired(queryParameter.getRequired()); - property.getVendorExtensions().put(VEN_FROM_QUERY, Boolean.TRUE); + if (Boolean.TRUE.equals(queryParameter.getRequired())) { + List required = new ArrayList(); + required.add(queryParameter.getName()); + } + + property.addExtension(VEN_FROM_QUERY, Boolean.TRUE); } } return property; } - protected String generateUniqueDefinitionName(String name, Swagger swagger) - { + protected String generateUniqueDefinitionName(String name, OpenAPI openAPI) { String result = name; - if (swagger.getDefinitions() != null) { + if (openAPI.getComponents().getSchemas() != null) { int count = 1; - while (swagger.getDefinitions().containsKey(result)) - { + while (openAPI.getComponents().getSchemas().containsKey(result)) { result = name + "_" + count; count += 1; } @@ -298,7 +311,7 @@ public Map postProcessOperations(Map objs) { protected String generatePathPattern(CodegenOperation op) { String result = op.path; for (CodegenParameter pp : op.pathParams) { - StringBuilder replacement = new StringBuilder( "{" + pp.paramName); + StringBuilder replacement = new StringBuilder("{" + pp.paramName); if (pp.isEnum) { StringBuilder enumRegExp = new StringBuilder(); for (String enumValue : pp._enum) { 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 5f9d98862c31..830a83565e2f 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 @@ -1,9 +1,12 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import org.openapitools.codegen.utils.ModelUtils; + import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -332,18 +335,18 @@ public String toModelFilename(String name) { * @return string presentation of the type **/ @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type; // This maps, for example, long -> Long based on hashes in this type's constructor - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) { return type; } } else { - type = swaggerType; + type = openAPIType; } // model/object @@ -353,21 +356,20 @@ public String getSwaggerType(Property p) { /** * Output the type declaration of the property * - * @param p Swagger Property object + * @param p OpenAPI Schema object * @return a string presentation of the property type */ @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return getTypeDeclaration(inner) + "[]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); // TODO not sure if the following map/hash declaration is correct return "{String, " + getTypeDeclaration(inner) + "}"; - } else if (!languageSpecificPrimitives.contains(getSwaggerType(p))) { + } else if (!languageSpecificPrimitives.contains(getSchemaType(p))) { return packageName + ".Model." + super.getTypeDeclaration(p); } return super.getTypeDeclaration(p); 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 old mode 100755 new mode 100644 index 1125c1035e70..a81a5f0a35a2 --- 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 @@ -9,7 +9,12 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.*; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.parser.util.SchemaTypeUtil; import java.io.File; import java.util.ArrayList; @@ -63,6 +68,9 @@ public PythonClientCodegen() { testFolder = "test"; + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("float"); @@ -98,16 +106,16 @@ public PythonClientCodegen() { // from https://docs.python.org/3/reference/lexical_analysis.html#keywords setReservedWordsLowerCase( Arrays.asList( - // local variable name used in API methods (endpoints) - "all_params", "resource_path", "path_params", "query_params", - "header_params", "form_params", "local_var_files", "body_params", "auth_settings", - // @property - "property", - // python reserved words - "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", - "assert", "else", "if", "pass", "yield", "break", "except", "import", - "print", "class", "exec", "in", "raise", "continue", "finally", "is", - "return", "def", "for", "lambda", "try", "self", "nonlocal", "None", "True", "False")); + // local variable name used in API methods (endpoints) + "all_params", "resource_path", "path_params", "query_params", + "header_params", "form_params", "local_var_files", "body_params", "auth_settings", + // @property + "property", + // python reserved words + "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", + "assert", "else", "if", "pass", "yield", "break", "except", "import", + "print", "class", "exec", "in", "raise", "continue", "finally", "is", + "return", "def", "for", "lambda", "try", "self", "nonlocal", "None", "True", "False")); regexModifiers = new HashMap(); regexModifiers.put('i', "IGNORECASE"); @@ -126,7 +134,7 @@ public PythonClientCodegen() { cliOptions.add(new CliOption(PACKAGE_URL, "python package URL.")); cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); supportedLibraries.put("urllib3", "urllib3-based client"); @@ -143,21 +151,19 @@ public void processOpts() { super.processOpts(); Boolean excludeTests = false; - if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { + if (additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString()); } if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - } - else { + } else { setPackageName("swagger_client"); } if (additionalProperties.containsKey(CodegenConstants.PROJECT_NAME)) { setProjectName((String) additionalProperties.get(CodegenConstants.PROJECT_NAME)); - } - else { + } else { // default: set project based on package name // e.g. petstore_api (package name) => petstore-api (project name) setProjectName(packageName.replaceAll("_", "-")); @@ -165,17 +171,8 @@ public void processOpts() { if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); - } - else { - setPackageVersion("1.0.0"); - } - - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + setPackageVersion("1.0.0"); } additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName); @@ -201,7 +198,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("__init__model.mustache", packageName + File.separatorChar + modelPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__api.mustache", packageName + File.separatorChar + apiPackage, "__init__.py")); - if(Boolean.FALSE.equals(excludeTests)) { + if (Boolean.FALSE.equals(excludeTests)) { supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py")); } supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); @@ -232,14 +229,14 @@ private static String dropDots(String str) { @Override public String toModelImport(String name) { String modelImport; - if (StringUtils.startsWithAny(name,"import", "from")) { + if (StringUtils.startsWithAny(name, "import", "from")) { modelImport = name; } else { modelImport = "from "; if (!"".equals(modelPackage())) { modelImport += modelPackage() + "."; } - modelImport += toModelFilename(name)+ " import " + name; + modelImport += toModelFilename(name) + " import " + name; } return modelImport; } @@ -251,7 +248,7 @@ public Map postProcessModels(Map objs) { } @Override - public void postProcessParameter(CodegenParameter parameter){ + public void postProcessParameter(CodegenParameter parameter) { postProcessPattern(parameter.pattern, parameter.vendorExtensions); } @@ -265,21 +262,21 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert * does not support this in as natural a way so it needs to convert it. See * https://docs.python.org/2/howto/regex.html#compilation-flags for details. */ - public void postProcessPattern(String pattern, Map vendorExtensions){ - if(pattern != null) { + public void postProcessPattern(String pattern, Map vendorExtensions) { + if (pattern != null) { int i = pattern.lastIndexOf('/'); //Must follow Perl /pattern/modifiers convention - if(pattern.charAt(0) != '/' || i < 2) { + if (pattern.charAt(0) != '/' || i < 2) { throw new IllegalArgumentException("Pattern must follow the Perl " - + "/pattern/modifiers convention. "+pattern+" is not valid."); + + "/pattern/modifiers convention. " + pattern + " is not valid."); } String regex = pattern.substring(1, i).replace("'", "\\'"); List modifiers = new ArrayList(); - for(char c : pattern.substring(i).toCharArray()) { - if(regexModifiers.containsKey(c)) { + for (char c : pattern.substring(i).toCharArray()) { + if (regexModifiers.containsKey(c)) { String modifier = regexModifiers.get(c); modifiers.add(modifier); } @@ -307,7 +304,7 @@ public String getHelp() { @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -355,23 +352,22 @@ public String modelTestFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); - return getSwaggerType(p) + "(str, " + getTypeDeclaration(inner) + ")"; + return getSchemaType(p) + "(str, " + getTypeDeclaration(inner) + ")"; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String swaggerType = super.getSchemaType(p); String type = null; if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); @@ -518,7 +514,7 @@ public void setPackageName(String packageName) { } public void setProjectName(String projectName) { - this.projectName= projectName; + this.projectName = projectName; } public void setPackageVersion(String packageVersion) { @@ -531,7 +527,7 @@ public void setPackageUrl(String packageUrl) { /** * Generate Python package name from String `packageName` - * + *

* (PEP 0008) Python packages should also have short, all-lowercase names, * although the use of underscores is discouraged. * @@ -550,46 +546,32 @@ public String generatePackageName(String packageName) { * @return string presentation of the default value of the property */ @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - if (Pattern.compile("\r\n|\r|\n").matcher(dp.getDefault()).find()) - return "'''" + dp.getDefault() + "'''"; - else - return "'" + dp.getDefault() + "'"; - } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getDefault() != null) { - if (dp.getDefault().toString().equalsIgnoreCase("false")) + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + if (p.getDefault().toString().equalsIgnoreCase("false")) return "False"; else return "True"; } - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { // TODO - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { // TODO - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find()) + return "'''" + p.getDefault() + "'''"; + else + return "'" + p.getDefault() + "'"; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlaskConnexionCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java similarity index 77% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlaskConnexionCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java index b8ed6ca4029c..4a390b1a3e25 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java @@ -6,13 +6,13 @@ import com.google.common.collect.Multimap; import org.openapitools.codegen.*; -import io.swagger.models.HttpMethod; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.Swagger; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.*; -import io.swagger.util.Yaml; +import org.openapitools.codegen.utils.ModelUtils; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.core.util.Yaml; import java.io.File; import java.util.*; @@ -21,13 +21,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConfig { - - private static final Logger LOGGER = LoggerFactory.getLogger(FlaskConnexionCodegen.class); +public class PythonFlaskConnexionServerCodegen extends DefaultCodegen implements CodegenConfig { + private static final Logger LOGGER = LoggerFactory.getLogger(PythonFlaskConnexionServerCodegen.class); public static final String CONTROLLER_PACKAGE = "controllerPackage"; public static final String DEFAULT_CONTROLLER = "defaultController"; - public static final String SUPPORT_PYTHON2= "supportPython2"; + public static final String SUPPORT_PYTHON2 = "supportPython2"; protected int serverPort = 8080; protected String packageName; @@ -36,7 +35,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf protected String defaultController; protected Map regexModifiers; - public FlaskConnexionCodegen() { + public PythonFlaskConnexionServerCodegen() { super(); modelPackage = "models"; testPackage = "test"; @@ -72,13 +71,13 @@ public FlaskConnexionCodegen() { // from https://docs.python.org/3/reference/lexical_analysis.html#keywords setReservedWordsLowerCase( Arrays.asList( - // @property - "property", - // python reserved words - "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", - "assert", "else", "if", "pass", "yield", "break", "except", "import", - "print", "class", "exec", "in", "raise", "continue", "finally", "is", - "return", "def", "for", "lambda", "try", "self", "None", "True", "False", "nonlocal")); + // @property + "property", + // python reserved words + "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", + "assert", "else", "if", "pass", "yield", "break", "except", "import", + "print", "class", "exec", "in", "raise", "continue", "finally", "is", + "return", "def", "for", "lambda", "try", "self", "None", "True", "False", "nonlocal")); // set the output folder here outputFolder = "generated-code/connexion"; @@ -178,7 +177,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("__init__model.mustache", packageName + File.separatorChar + modelPackage, "__init__.py")); supportingFiles.add(new SupportingFile("base_model_.mustache", packageName + File.separatorChar + modelPackage, "base_model_.py")); supportingFiles.add(new SupportingFile("__init__test.mustache", packageName + File.separatorChar + testPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("swagger.mustache", packageName + File.separatorChar + "swagger", "swagger.yaml")); + supportingFiles.add(new SupportingFile("openapi.mustache", packageName + File.separatorChar + "openapi", "openapi.yaml")); modelPackage = packageName + "." + modelPackage; controllerPackage = packageName + "." + controllerPackage; @@ -194,7 +193,6 @@ public String apiPackage() { return controllerPackage; } - /** * Configures the type of generator. * @@ -226,7 +224,7 @@ public String getName() { @Override public String getHelp() { return "Generates a Python server library using the Connexion project. By default, " + - "it will also generate service classes -- which you can disable with the `-Dnoservice` environment variable."; + "it will also generate service classes -- which you can disable with the `-Dnoservice` environment variable."; } @Override @@ -254,13 +252,13 @@ public String toApiTestFilename(String name) { * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; // add an underscore to the name } - + /** * Location to write api files. You can use the apiPackage() as defined when the class is * instantiated @@ -271,70 +269,59 @@ public String apiFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[str, " + getTypeDeclaration(inner) + "]"; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[str, " + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); if (languageSpecificPrimitives.contains(type)) { return type; } } else { - type = toModelName(swaggerType); + type = toModelName(schemaType); } return type; } @Override - public void preprocessSwagger(Swagger swagger) { + public void preprocessOpenAPI(OpenAPI openAPI) { // need vendor extensions for x-swagger-router-controller - Map paths = swagger.getPaths(); - if(paths != null) { - for(String pathname : paths.keySet()) { - Path path = paths.get(pathname); - Map operationMap = path.getOperationMap(); - if(operationMap != null) { - for(HttpMethod method : operationMap.keySet()) { + Map paths = openAPI.getPaths(); + if (paths != null) { + for (String pathname : paths.keySet()) { + PathItem path = paths.get(pathname); + Map operationMap = path.readOperationsMap(); + if (operationMap != null) { + for (HttpMethod method : operationMap.keySet()) { Operation operation = operationMap.get(method); String tag = "default"; - if(operation.getTags() != null && operation.getTags().size() > 0) { + if (operation.getTags() != null && operation.getTags().size() > 0) { tag = operation.getTags().get(0); } String operationId = operation.getOperationId(); - if(operationId == null) { + if (operationId == null) { operationId = getOrGenerateOperationId(operation, pathname, method.toString()); } operation.setOperationId(toOperationId(operationId)); - if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) { - operation.getVendorExtensions().put( + if (operation.getExtensions().get("x-swagger-router-controller") == null) { + operation.addExtension( "x-swagger-router-controller", controllerPackage + "." + toApiFilename(tag) ); } - for (Parameter param: operation.getParameters()) { - // sanitize the param name but don't underscore it since it's used for request mapping - String name = param.getName(); - String paramName = sanitizeName(name); - if (!paramName.equals(name)) { - LOGGER.warn(name + " cannot be used as parameter name with flask-connexion and was sanitized as " + paramName); - } - param.setName(paramName); - } } } } @@ -377,14 +364,8 @@ private static List> sortOperationsByPath(List postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { - try { - objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } + generateYAMLSpecFile(objs); + for (Map operations : getOperations(objs)) { @SuppressWarnings("unchecked") List ops = (List) operations.get("operation"); @@ -425,12 +406,13 @@ public String toVarName(String name) { @Override public String toParamName(String name) { - // don't do name =removeNonNameElementToCamelCase(name); // this breaks connexion, which does not modify param names before sending them - if (reservedWords.contains(name)) { - return escapeReservedWord(name); + // to avoid conflicts with 'callback' parameter for async call + if ("callback".equals(name)) { + return "param_callback"; } - // Param name is already sanitized in swagger spec processing - return name; + + // should be the same as variable name + return toVarName(name); } @Override @@ -494,43 +476,29 @@ public String toOperationId(String operationId) { * @return string presentation of the default value of the property */ @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - return "'" + dp.getDefault() + "'"; - } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getDefault() != null) { - if (dp.getDefault().toString().equalsIgnoreCase("false")) + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + if (p.getDefault().toString().equalsIgnoreCase("false")) return "False"; else return "True"; } - } else if (p instanceof DateProperty) { + } else if (ModelUtils.isDateSchema(p)) { // TODO - } else if (p instanceof DateTimeProperty) { + } else if (ModelUtils.isDateTimeSchema(p)) { // TODO - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return "'" + (String) p.getDefault() + "'"; } } @@ -558,28 +526,28 @@ public void setParameterExampleValue(CodegenParameter p) { } example = "'" + escapeText(example) + "'"; } else if ("Integer".equals(type) || "int".equals(type)) { - if(p.minimum != null) { + if (p.minimum != null) { example = "" + (Integer.valueOf(p.minimum) + 1); } - if(p.maximum != null) { + if (p.maximum != null) { example = "" + p.maximum; } else if (example == null) { example = "56"; } } else if ("Long".equalsIgnoreCase(type)) { - if(p.minimum != null) { + if (p.minimum != null) { example = "" + (Long.valueOf(p.minimum) + 1); } - if(p.maximum != null) { + if (p.maximum != null) { example = "" + p.maximum; } else if (example == null) { example = "789"; } } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { - if(p.minimum != null) { + if (p.minimum != null) { example = "" + p.minimum; - } else if(p.maximum != null) { + } else if (p.maximum != null) { example = "" + p.maximum; } else if (example == null) { example = "3.4"; @@ -607,7 +575,7 @@ public void setParameterExampleValue(CodegenParameter p) { LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); } - if(p.items != null && p.items.defaultValue != null) { + if (p.items != null && p.items.defaultValue != null) { example = p.items.defaultValue; } if (example == null) { @@ -647,20 +615,20 @@ public String escapeUnsafeCharacters(String input) { @Override public String toModelImport(String name) { String modelImport; - if (StringUtils.startsWithAny(name,"import", "from")) { + if (StringUtils.startsWithAny(name, "import", "from")) { modelImport = name; } else { modelImport = "from "; if (!"".equals(modelPackage())) { modelImport += modelPackage() + "."; } - modelImport += toModelFilename(name)+ " import " + name; + modelImport += toModelFilename(name) + " import " + name; } return modelImport; } @Override - public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { if (StringUtils.isNotEmpty(property.pattern)) { addImport(model, "import re"); } @@ -674,30 +642,30 @@ public Map postProcessModels(Map objs) { } @Override - public void postProcessParameter(CodegenParameter parameter){ + public void postProcessParameter(CodegenParameter parameter) { postProcessPattern(parameter.pattern, parameter.vendorExtensions); } /* - * The swagger pattern spec follows the Perl convention and style of modifiers. Python + * The openapi pattern spec follows the Perl convention and style of modifiers. Python * does not support this in as natural a way so it needs to convert it. See * https://docs.python.org/2/howto/regex.html#compilation-flags for details. */ - public void postProcessPattern(String pattern, Map vendorExtensions){ - if(pattern != null) { + public void postProcessPattern(String pattern, Map vendorExtensions) { + if (pattern != null) { int i = pattern.lastIndexOf('/'); //Must follow Perl /pattern/modifiers convention - if(pattern.charAt(0) != '/' || i < 2) { + if (pattern.charAt(0) != '/' || i < 2) { throw new IllegalArgumentException("Pattern must follow the Perl " - + "/pattern/modifiers convention. "+pattern+" is not valid."); + + "/pattern/modifiers convention. " + pattern + " is not valid."); } String regex = pattern.substring(1, i).replace("'", "\\'"); List modifiers = new ArrayList(); - for(char c : pattern.substring(i).toCharArray()) { - if(regexModifiers.containsKey(c)) { + for (char c : pattern.substring(i).toCharArray()) { + if (regexModifiers.containsKey(c)) { String modifier = regexModifiers.get(c); modifiers.add(modifier); } 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 2712bbe66b34..9b37ae23d7f3 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 @@ -1,10 +1,11 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.parameters.Parameter; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import java.io.File; import java.util.*; @@ -45,6 +46,9 @@ public RClientCodegen() { embeddedTemplateDir = templateDir = "r"; + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + setReservedWordsLowerCase( Arrays.asList( // reserved words: https://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html @@ -93,7 +97,7 @@ public RClientCodegen() { .defaultValue("swagger")); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "R package version.") .defaultValue("1.0.0")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); } @@ -102,14 +106,6 @@ public RClientCodegen() { public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } else { @@ -274,45 +270,44 @@ public String toApiName(String name) { } @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if(ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return getTypeDeclaration(inner); - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return getTypeDeclaration(inner); } // Not using the supertype invocation, because we want to UpperCamelize // the type. - String swaggerType = getSwaggerType(p); - if (typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); + String openAPIType = getSchemaType(p); + if (typeMapping.containsKey(openAPIType)) { + return typeMapping.get(openAPIType); } - if (typeMapping.containsValue(swaggerType)) { - return swaggerType; + if (typeMapping.containsValue(openAPIType)) { + return openAPIType; } - if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; + if (languageSpecificPrimitives.contains(openAPIType)) { + return openAPIType; } - return toModelName(swaggerType); + return toModelName(openAPIType); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) return (type); } else { - type = swaggerType; + type = openAPIType; } return type; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RestbedCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RestbedCodegen.java deleted file mode 100644 index 2f576012344c..000000000000 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RestbedCodegen.java +++ /dev/null @@ -1,407 +0,0 @@ -package org.openapitools.codegen.languages; - -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.Map; -import java.util.Set; - -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenParameter; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.SupportingFile; -import io.swagger.models.Model; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BaseIntegerProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DecimalProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FileProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; - -public class RestbedCodegen extends AbstractCppCodegen { - - public static final String DECLSPEC = "declspec"; - public static final String DEFAULT_INCLUDE = "defaultInclude"; - - protected String packageVersion = "1.0.0"; - protected String declspec = ""; - protected String defaultInclude = ""; - - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see org.openapitools.codegen.CodegenType - */ - public CodegenType getTag() { - return CodegenType.SERVER; - } - - /** - * Configures a friendly name for the generator. This will be used by the - * generator to select the library with the -l flag. - * - * @return the friendly name for the generator - */ - public String getName() { - return "restbed"; - } - - /** - * Returns human-friendly help for the generator. Provide the consumer with - * help tips, parameters here - * - * @return A string value for the help message - */ - public String getHelp() { - return "Generates a C++ API Server with Restbed (https://github.com/Corvusoft/restbed)."; - } - - public RestbedCodegen() { - super(); - - apiPackage = "io.swagger.server.api"; - modelPackage = "io.swagger.server.model"; - - modelTemplateFiles.put("model-header.mustache", ".h"); - modelTemplateFiles.put("model-source.mustache", ".cpp"); - - apiTemplateFiles.put("api-header.mustache", ".h"); - apiTemplateFiles.put("api-source.mustache", ".cpp"); - - embeddedTemplateDir = templateDir = "restbed"; - - cliOptions.clear(); - - // CLI options - addOption(CodegenConstants.MODEL_PACKAGE, "C++ namespace for models (convention: name.space.model).", - this.modelPackage); - addOption(CodegenConstants.API_PACKAGE, "C++ namespace for apis (convention: name.space.api).", - this.apiPackage); - addOption(CodegenConstants.PACKAGE_VERSION, "C++ package version.", this.packageVersion); - addOption(DECLSPEC, "C++ preprocessor to place before the class name for handling dllexport/dllimport.", - this.declspec); - addOption(DEFAULT_INCLUDE, - "The default include statement that should be placed in all headers for including things like the declspec (convention: #include \"Commons.h\" ", - this.defaultInclude); - - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - - languageSpecificPrimitives = new HashSet( - Arrays.asList("int", "char", "bool", "long", "float", "double", "int32_t", "int64_t")); - - typeMapping = new HashMap(); - typeMapping.put("date", "std::string"); - typeMapping.put("DateTime", "std::string"); - typeMapping.put("string", "std::string"); - typeMapping.put("integer", "int32_t"); - typeMapping.put("long", "int64_t"); - typeMapping.put("boolean", "bool"); - typeMapping.put("array", "std::vector"); - typeMapping.put("map", "std::map"); - typeMapping.put("file", "std::string"); - typeMapping.put("object", "Object"); - typeMapping.put("binary", "restbed::Bytes"); - typeMapping.put("number", "double"); - typeMapping.put("UUID", "std::string"); - - super.importMapping = new HashMap(); - importMapping.put("std::vector", "#include "); - importMapping.put("std::map", "#include "); - importMapping.put("std::string", "#include "); - importMapping.put("Object", "#include \"Object.h\""); - importMapping.put("restbed::Bytes", "#include "); - } - - protected void addOption(String key, String description, String defaultValue) { - CliOption option = new CliOption(key, description); - if (defaultValue != null) - option.defaultValue(defaultValue); - cliOptions.add(option); - } - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(DECLSPEC)) { - declspec = additionalProperties.get(DECLSPEC).toString(); - } - - if (additionalProperties.containsKey(DEFAULT_INCLUDE)) { - defaultInclude = additionalProperties.get(DEFAULT_INCLUDE).toString(); - } - - additionalProperties.put("modelNamespaceDeclarations", modelPackage.split("\\.")); - additionalProperties.put("modelNamespace", modelPackage.replaceAll("\\.", "::")); - additionalProperties.put("apiNamespaceDeclarations", apiPackage.split("\\.")); - additionalProperties.put("apiNamespace", apiPackage.replaceAll("\\.", "::")); - additionalProperties.put("declspec", declspec); - additionalProperties.put("defaultInclude", defaultInclude); - } - - /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle - * escaping those terms here. This logic is only called if a variable - * matches the reserved words - * - * @return the escaped term - */ - @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name - } - - /** - * Location to write model files. You can use the modelPackage() as defined - * when the class is instantiated - */ - public String modelFileFolder() { - return (outputFolder + "/model").replace("/", File.separator); - } - - /** - * Location to write api files. You can use the apiPackage() as defined when - * the class is instantiated - */ - @Override - public String apiFileFolder() { - return (outputFolder + "/api").replace("/", File.separator); - } - - @Override - public String toModelImport(String name) { - if (importMapping.containsKey(name)) { - return importMapping.get(name); - } else { - return "#include \"" + name + ".h\""; - } - } - - @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { - CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); - - Set oldImports = codegenModel.imports; - codegenModel.imports = new HashSet(); - for (String imp : oldImports) { - String newImp = toModelImport(imp); - if (!newImp.isEmpty()) { - codegenModel.imports.add(newImp); - } - } - - return codegenModel; - } - - - @Override - public String toModelFilename(String name) { - return initialCaps(name); - } - - @Override - public String toApiFilename(String name) { - return initialCaps(name) + "Api"; - } - - @SuppressWarnings("unchecked") - @Override - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - List operationList = (List) operations.get("operation"); - List newOpList = new ArrayList(); - for (CodegenOperation op : operationList) { - String path = new String(op.path); - - String[] items = path.split("/", -1); - String resourceNameCamelCase = ""; - op.path = ""; - for (String item: items) { - if (item.length() > 1) { - if (item.matches("^\\{(.*)\\}$")) { - String tmpResourceName = item.substring(1, item.length()-1); - resourceNameCamelCase += Character.toUpperCase(tmpResourceName.charAt(0)) + tmpResourceName.substring(1); - item = item.substring(0, item.length()-1); - item += ": .*}"; - } else { - resourceNameCamelCase += Character.toUpperCase(item.charAt(0)) + item.substring(1); - } - } else if (item.length() == 1) { - resourceNameCamelCase += Character.toUpperCase(item.charAt(0)); - } - op.path += item + "/"; - } - op.vendorExtensions.put("x-codegen-resourceName", resourceNameCamelCase); - boolean foundInNewList = false; - for (CodegenOperation op1 : newOpList) { - if (!foundInNewList) { - if (op1.path.equals(op.path)) { - foundInNewList = true; - List currentOtherMethodList = (List) op1.vendorExtensions.get("x-codegen-otherMethods"); - if (currentOtherMethodList == null) { - currentOtherMethodList = new ArrayList(); - } - op.operationIdCamelCase = op1.operationIdCamelCase; - currentOtherMethodList.add(op); - op1.vendorExtensions.put("x-codegen-otherMethods", currentOtherMethodList); - } - } - } - if (!foundInNewList) { - newOpList.add(op); - } - } - operations.put("operation", newOpList); - return objs; - } - - /** - * Optional - type declaration. This is a String which is used by the - * templates to instantiate your types. There is typically special handling - * for different property types - * - * @return a string value used as the `dataType` field for model templates, - * `returnType` for api templates - */ - @Override - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } - if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; - } - if (p instanceof StringProperty || p instanceof DateProperty - || p instanceof DateTimeProperty || p instanceof FileProperty - || languageSpecificPrimitives.contains(swaggerType)) { - return toModelName(swaggerType); - } - - return "std::shared_ptr<" + swaggerType + ">"; - } - - @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "\"\""; - } else if (p instanceof BooleanProperty) { - return "false"; - } else if (p instanceof DateProperty) { - return "\"\""; - } else if (p instanceof DateTimeProperty) { - return "\"\""; - } else if (p instanceof DoubleProperty) { - return "0.0"; - } else if (p instanceof FloatProperty) { - return "0.0f"; - } else if (p instanceof LongProperty) { - return "0L"; - } else if (p instanceof IntegerProperty || p instanceof BaseIntegerProperty) { - return "0"; - } else if (p instanceof DecimalProperty) { - return "0.0"; - } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "std::map()"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - if (!languageSpecificPrimitives.contains(inner)) { - inner = "std::shared_ptr<" + inner + ">"; - } - return "std::vector<" + inner + ">()"; - } else if (p instanceof RefProperty) { - RefProperty rp = (RefProperty) p; - return "new " + toModelName(rp.getSimpleRef()) + "()"; - } - return "nullptr"; - } - - @Override - public void postProcessParameter(CodegenParameter parameter) { - super.postProcessParameter(parameter); - - boolean isPrimitiveType = parameter.isPrimitiveType == Boolean.TRUE; - boolean isListContainer = parameter.isListContainer == Boolean.TRUE; - boolean isString = parameter.isString == Boolean.TRUE; - - if (!isPrimitiveType && !isListContainer && !isString && !parameter.dataType.startsWith("std::shared_ptr")) { - parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">"; - } - } - - /** - * Optional - swagger type conversion. This is used to map swagger types in - * a `Property` into either language specific types via `typeMapping` or - * into complex models if there is not a mapping. - * - * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property - */ - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) - return toModelName(type); - } else - type = swaggerType; - return toModelName(type); - } - - @Override - public String toModelName(String type) { - if (typeMapping.keySet().contains(type) || typeMapping.values().contains(type) - || importMapping.values().contains(type) || defaultIncludes.contains(type) - || languageSpecificPrimitives.contains(type)) { - return type; - } else { - return Character.toUpperCase(type.charAt(0)) + type.substring(1); - } - } - - @Override - public String toApiName(String type) { - return Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api"; - } - - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").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 bfe168e0d4d9..003b3032c6e4 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 @@ -1,5 +1,6 @@ package org.openapitools.codegen.languages; +import io.swagger.v3.oas.models.media.*; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenConstants; @@ -9,17 +10,16 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.models.properties.*; +import org.openapitools.codegen.utils.ModelUtils; import java.io.File; import java.util.Arrays; -import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Map; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -73,17 +73,20 @@ public RubyClientCodegen() { modelTestTemplateFiles.put("model_test.mustache", ".rb"); apiTestTemplateFiles.put("api_test.mustache", ".rb"); + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + setReservedWordsLowerCase( Arrays.asList( - // local variable names used in API methods (endpoints) - "local_var_path", "query_params", "header_params", "_header_accept", "_header_accept_result", - "_header_content_type", "form_params", "post_body", "auth_names", - // ruby reserved keywords - "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", - "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", - "break", "do", "false", "next", "rescue", "then", "when", "END", "case", - "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", - "if", "not", "return", "undef", "yield") + // local variable names used in API methods (endpoints) + "local_var_path", "query_params", "header_params", "_header_accept", "_header_accept_result", + "_header_content_type", "form_params", "post_body", "auth_names", + // ruby reserved keywords + "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", + "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", + "break", "do", "false", "next", "rescue", "then", "when", "END", "case", + "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", + "if", "not", "return", "undef", "yield") ); typeMapping.clear(); @@ -161,7 +164,7 @@ public RubyClientCodegen() { cliOptions.add(new CliOption(GEM_AUTHOR_EMAIL, "gem author email (only one is supported).")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated"). + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC). defaultValue(Boolean.TRUE.toString())); } @@ -170,14 +173,6 @@ public RubyClientCodegen() { public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - if (additionalProperties.containsKey(GEM_NAME)) { setGemName((String) additionalProperties.get(GEM_NAME)); } @@ -199,7 +194,7 @@ public void processOpts() { if (additionalProperties.containsKey(GEM_VERSION)) { setGemVersion((String) additionalProperties.get(GEM_VERSION)); - }else { + } else { // not set, pass the default value to template additionalProperties.put(GEM_VERSION, gemVersion); } @@ -263,35 +258,37 @@ public void processOpts() { //writeOptional(outputFolder, new SupportingFile("base_object_spec.mustache", specFolder, "base_object_spec.rb")); } - @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); - // Set vendor-extension to be used in template: - // x-codegen-hasMoreRequired - // x-codegen-hasMoreOptional - // x-codegen-hasRequiredParams - CodegenParameter lastRequired = null; - CodegenParameter lastOptional = null; - for (CodegenParameter p : op.allParams) { - if (p.required) { - lastRequired = p; - } else { - lastOptional = p; + /* TO BE DELETED: replaced with postProcessOperations below + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map schemas, OpenAPI openAPI) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, schemas, openAPI); + // Set vendor-extension to be used in template: + // x-codegen-hasMoreRequired + // x-codegen-hasMoreOptional + // x-codegen-hasRequiredParams + CodegenParameter lastRequired = null; + CodegenParameter lastOptional = null; + for (CodegenParameter p : op.allParams) { + if (p.required) { + lastRequired = p; + } else { + lastOptional = p; + } } - } - for (CodegenParameter p : op.allParams) { - if (p == lastRequired) { - p.vendorExtensions.put("x-codegen-hasMoreRequired", false); - } else if (p == lastOptional) { - p.vendorExtensions.put("x-codegen-hasMoreOptional", false); - } else { - p.vendorExtensions.put("x-codegen-hasMoreRequired", true); - p.vendorExtensions.put("x-codegen-hasMoreOptional", true); + for (CodegenParameter p : op.allParams) { + if (p == lastRequired) { + p.vendorExtensions.put("x-codegen-hasMoreRequired", false); + } else if (p == lastOptional) { + p.vendorExtensions.put("x-codegen-hasMoreOptional", false); + } else { + p.vendorExtensions.put("x-codegen-hasMoreRequired", true); + p.vendorExtensions.put("x-codegen-hasMoreOptional", true); + } } + op.vendorExtensions.put("x-codegen-hasRequiredParams", lastRequired != null); + return op; } - op.vendorExtensions.put("x-codegen-hasRequiredParams", lastRequired != null); - return op; - } + */ @Override public CodegenType getTag() { @@ -322,7 +319,7 @@ public String generateModuleName(String gemName) { /** * Generate Ruby gem name from the module name, e.g. use "swagger_client" for "SwaggerClient". * - * @param moduleName Ruby module naame + * @param moduleName Ruby module naame * @return Ruby gem name */ @SuppressWarnings("static-method") @@ -331,8 +328,8 @@ public String generateGemName(String moduleName) { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -369,50 +366,27 @@ public String modelDocFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; + public String getTypeDeclaration(Schema schema) { + if (ModelUtils.isArraySchema(schema)) { + Schema inner = ((ArraySchema) schema).getItems(); + return getSchemaType(schema) + "<" + getTypeDeclaration(inner) + ">"; + } else if (ModelUtils.isMapSchema(schema)) { + Schema inner = (Schema) schema.getAdditionalProperties(); + return getSchemaType(schema) + ""; } - return super.getTypeDeclaration(p); + + return super.getTypeDeclaration(schema); } @Override - public String toDefaultValue(Property p) { - if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + public String toDefaultValue(Schema p) { + if (ModelUtils.isIntegerSchema(p)|| ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof BooleanProperty) { - BooleanProperty bp = (BooleanProperty) p; - if (bp.getDefault() != null) { - return bp.getDefault().toString(); - } - } else if (p instanceof StringProperty) { - StringProperty sp = (StringProperty) p; - if (sp.getDefault() != null) { - return "'" + escapeText(sp.getDefault()) + "'"; + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return "'" + escapeText((String) p.getDefault()) + "'"; } } @@ -420,20 +394,22 @@ public String toDefaultValue(Property p) { } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema schema) { + String openAPIType = super.getSchemaType(schema); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) { return type; } } else { - type = swaggerType; + type = openAPIType; } + if (type == null) { return null; } + return toModelName(type); } @@ -496,31 +472,7 @@ public String toModelName(String name) { @Override public String toModelFilename(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - if (!StringUtils.isEmpty(modelNamePrefix)) { - name = modelNamePrefix + "_" + name; - } - - if (!StringUtils.isEmpty(modelNameSuffix)) { - name = name + "_" + modelNameSuffix; - } - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(name)) { - String filename = underscore("model_" + name); - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + filename); - return filename; - } - - // 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 " + underscore("model_" + name)); - name = "model_" + name; // e.g. 200Response => model_200_response - } - - // underscore the model file name - // PhoneNumber.rb => phone_number.rb - return underscore(name); + return underscore(toModelName(name)); } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Rails5ServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java similarity index 91% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Rails5ServerCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java index 57d9d99ab560..feb1bead3685 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Rails5ServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java @@ -8,11 +8,12 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.Swagger; -import io.swagger.util.Yaml; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.core.util.Yaml; import java.io.File; import java.util.Arrays; @@ -23,9 +24,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig { +public class RubyOnRailsServerCodegen extends DefaultCodegen implements CodegenConfig { - private static final Logger LOGGER = LoggerFactory.getLogger(Rails5ServerCodegen.class); + private static final Logger LOGGER = LoggerFactory.getLogger(RubyOnRailsServerCodegen.class); private static final SimpleDateFormat MIGRATE_FILE_NAME_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss"); protected String gemName; @@ -58,7 +59,7 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig protected String socketsFolder = tmpFolder + File.separator + "sockets"; protected String vendorFolder = "vendor"; - public Rails5ServerCodegen() { + public RubyOnRailsServerCodegen() { super(); outputFolder = "generated-code" + File.separator + "rails5"; apiPackage = "app/controllers"; @@ -177,12 +178,12 @@ public CodegenType getTag() { @Override public String getName() { - return "rails5"; + return "ruby-on-rails"; } @Override public String getHelp() { - return "Generates a Rails5 server library."; + return "Generates a Ruby on Rails (v5) server library."; } @Override @@ -199,21 +200,20 @@ public String apiFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } @Override - public String toDefaultValue(Property p) { + public String toDefaultValue(Schema p) { return "null"; } @@ -240,8 +240,8 @@ public String toVarName(String name) { } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String swaggerType = super.getSchemaType(p); String type = null; if (typeMapping.containsKey(swaggerType)) { return typeMapping.get(swaggerType); @@ -315,14 +315,7 @@ public String toOperationId(String operationId) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { - try { - objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } + generateYAMLSpecFile(objs); return super.postProcessSupportingFileData(objs); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SinatraServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java similarity index 81% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SinatraServerCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java index 87ab21a695e2..1253b5fef635 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SinatraServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java @@ -6,11 +6,12 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.Swagger; -import io.swagger.util.Yaml; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.core.util.Yaml; import java.io.File; import java.util.Arrays; @@ -21,16 +22,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfig { +public class RubySinatraServerCodegen extends DefaultCodegen implements CodegenConfig { - private static final Logger LOGGER = LoggerFactory.getLogger(SinatraServerCodegen.class); + private static final Logger LOGGER = LoggerFactory.getLogger(RubySinatraServerCodegen.class); protected String gemName; protected String moduleName; protected String gemVersion = "1.0.0"; protected String libFolder = "lib"; - public SinatraServerCodegen() { + public RubySinatraServerCodegen() { super(); apiPackage = "lib"; outputFolder = "generated-code" + File.separator + "sinatra"; @@ -86,7 +87,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("config.ru", "", "config.ru")); supportingFiles.add(new SupportingFile("Gemfile", "", "Gemfile")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); - supportingFiles.add(new SupportingFile("swagger.mustache","","swagger.yaml")); + supportingFiles.add(new SupportingFile("openapi.mustache","","openapi.yaml")); } @Override @@ -96,12 +97,12 @@ public CodegenType getTag() { @Override public String getName() { - return "sinatra"; + return "ruby-sinatra"; } @Override public String getHelp() { - return "Generates a Sinatra server library."; + return "Generates a Ruby Sinatra server library."; } @Override @@ -118,30 +119,29 @@ public String apiFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) { return type; } } else { - type = swaggerType; + type = openAPIType; } if (type == null) { return null; @@ -150,7 +150,7 @@ public String getSwaggerType(Property p) { } @Override - public String toDefaultValue(Property p) { + public String toDefaultValue(Schema p) { return "null"; } @@ -240,14 +240,7 @@ public String toOperationId(String operationId) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { - try { - objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } + generateYAMLSpecFile(objs); return super.postProcessSupportingFileData(objs); } 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 ca19c651a991..de45c829961e 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 @@ -1,10 +1,15 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.parameters.Parameter; +import org.openapitools.codegen.utils.*; +import org.openapitools.codegen.mustache.*; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; import java.io.File; import java.util.*; @@ -47,6 +52,9 @@ public RustClientCodegen() { modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + embeddedTemplateDir = templateDir = "rust"; setReservedWordsLowerCase( @@ -109,7 +117,7 @@ public RustClientCodegen() { .defaultValue("swagger")); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Rust package version.") .defaultValue("1.0.0")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); } @@ -118,14 +126,6 @@ public RustClientCodegen() { public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } @@ -272,49 +272,48 @@ public String toApiDocFilename(String name) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return "Vec<" + getTypeDeclaration(inner) + ">"; } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return "::std::collections::HashMap"; } // Not using the supertype invocation, because we want to UpperCamelize // the type. - String swaggerType = getSwaggerType(p); - if (typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); + String schemaType = getSchemaType(p); + if (typeMapping.containsKey(schemaType)) { + return typeMapping.get(schemaType); } - if (typeMapping.containsValue(swaggerType)) { - return swaggerType; + if (typeMapping.containsValue(schemaType)) { + return schemaType; } - if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; + if (languageSpecificPrimitives.contains(schemaType)) { + return schemaType; } // return fully-qualified model name // ::models::{{classnameFile}}::{{classname}} - return "::models::" + toModelName(swaggerType); + return "::models::" + toModelName(schemaType); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if(typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); if(languageSpecificPrimitives.contains(type)) return (type); } else - type = swaggerType; + type = schemaType; return type; } 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 old mode 100755 new mode 100644 index 30a635da891c..f0a64b3ab82b --- 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 @@ -1,21 +1,20 @@ package org.openapitools.codegen.languages; -import com.fasterxml.jackson.core.JsonProcessingException; import org.openapitools.codegen.*; -import io.swagger.models.*; -import io.swagger.models.parameters.BodyParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.*; -import io.swagger.util.Yaml; +import org.openapitools.codegen.utils.*; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.oas.models.info.Info; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; +import java.net.URL; import java.util.*; import java.util.Map.Entry; + import org.apache.commons.lang3.StringUtils; public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { @@ -34,6 +33,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { protected String packageName; protected String packageVersion; protected String externCrateName; + protected Map> pathSetMap = new HashMap>(); public RustServerCodegen() { super(); @@ -66,42 +66,42 @@ public RustServerCodegen() { * Reserved words. Override this with reserved words specific to your language */ setReservedWordsLowerCase( - Arrays.asList( - // From https://doc.rust-lang.org/grammar.html#keywords - "abstract", "alignof", "as", "become", "box", "break", "const", - "continue", "crate", "do", "else", "enum", "extern", "false", - "final", "fn", "for", "if", "impl", "in", "let", "loop", "macro", - "match", "mod", "move", "mut", "offsetof", "override", "priv", - "proc", "pub", "pure", "ref", "return", "Self", "self", "sizeof", - "static", "struct", "super", "trait", "true", "type", "typeof", - "unsafe", "unsized", "use", "virtual", "where", "while", "yield" - ) + Arrays.asList( + // From https://doc.rust-lang.org/grammar.html#keywords + "abstract", "alignof", "as", "become", "box", "break", "const", + "continue", "crate", "do", "else", "enum", "extern", "false", + "final", "fn", "for", "if", "impl", "in", "let", "loop", "macro", + "match", "mod", "move", "mut", "offsetof", "override", "priv", + "proc", "pub", "pure", "ref", "return", "Self", "self", "sizeof", + "static", "struct", "super", "trait", "true", "type", "typeof", + "unsafe", "unsized", "use", "virtual", "where", "while", "yield" + ) ); defaultIncludes = new HashSet( Arrays.asList( - "map", - "array") - ); + "map", + "array") + ); languageSpecificPrimitives = new HashSet( - Arrays.asList( - "bool", - "char", - "i8", - "i16", - "i32", - "i64", - "u8", - "u16", - "u32", - "u64", - "isize", - "usize", - "f32", - "f64", - "str") - ); + Arrays.asList( + "bool", + "char", + "i8", + "i16", + "i32", + "i64", + "u8", + "u16", + "u32", + "u64", + "isize", + "usize", + "f32", + "f64", + "str") + ); instantiationTypes.clear(); instantiationTypes.put("array", "Vec"); @@ -131,11 +131,11 @@ public RustServerCodegen() { cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, - "Rust crate name (convention: snake_case).") - .defaultValue("swagger_client")); + "Rust crate name (convention: snake_case).") + .defaultValue("swagger_client")); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, - "Rust crate version.") - .defaultValue("1.0.0")); + "Rust crate version.") + .defaultValue("1.0.0")); /* * Additional Properties. These values can be passed to the templates and @@ -155,8 +155,9 @@ public RustServerCodegen() { supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); supportingFiles.add(new SupportingFile("lib.mustache", "src", "lib.rs")); supportingFiles.add(new SupportingFile("models.mustache", "src", "models.rs")); - supportingFiles.add(new SupportingFile("server.mustache", "src", "server.rs")); - supportingFiles.add(new SupportingFile("client.mustache", "src", "client.rs")); + supportingFiles.add(new SupportingFile("server-mod.mustache", "src/server", "mod.rs")); + supportingFiles.add(new SupportingFile("server-auth.mustache", "src/server", "auth.rs")); + supportingFiles.add(new SupportingFile("client-mod.mustache", "src/client", "mod.rs")); supportingFiles.add(new SupportingFile("mimetypes.mustache", "src", "mimetypes.rs")); supportingFiles.add(new SupportingFile("example-server.mustache", "examples", "server.rs")); supportingFiles.add(new SupportingFile("example-client.mustache", "examples", "client.rs")); @@ -174,15 +175,13 @@ public void processOpts() { if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - } - else { + } else { setPackageName("swagger_client"); } if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); - } - else { + } else { setPackageVersion("1.0.0"); } @@ -241,8 +240,8 @@ public String getHelp() { } @Override - public void preprocessSwagger(Swagger swagger) { - Info info = swagger.getInfo(); + public void preprocessOpenAPI(OpenAPI openAPI) { + Info info = openAPI.getInfo(); List versionComponents = new ArrayList(Arrays.asList(info.getVersion().split("[.]"))); if (versionComponents.size() < 1) { versionComponents.add("1"); @@ -252,22 +251,9 @@ public void preprocessSwagger(Swagger swagger) { } info.setVersion(StringUtils.join(versionComponents, ".")); - String host = swagger.getHost(); - if (host != null) { - String[] parts = host.split(":"); - if (parts.length > 1) { - serverHost = parts[0]; - try { - serverPort = Integer.valueOf(parts[1]); - } catch (NumberFormatException e) { - LOGGER.warn("Port of Swagger host is not an integer : " + host, e); - } - } else { - serverHost = host; - } - } - additionalProperties.put("serverHost", serverHost); - additionalProperties.put("serverPort", serverPort); + URL url = URLPathUtils.getServerURL(openAPI); + additionalProperties.put("serverHost", url.getHost()); + additionalProperties.put("serverPort", url.getPort()); } @Override @@ -448,93 +434,80 @@ boolean isMimetypePlainText(String mimetype) { return mimetype.toLowerCase().startsWith("text/plain"); } + boolean isMimetypeWwwFormUrlEncoded(String mimetype) { + return mimetype.toLowerCase().startsWith("application/x-www-form-urlencoded"); + } + @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, OpenAPI openAPI) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, openAPI); + + // The Rust code will need to contain a series of regular expressions. + // For performance, we'll construct these at start-of-day and re-use + // them. That means we need labels for them. + // + // Construct a Rust constant (uppercase) token name, and ensure it's + // unique using a numeric tie-breaker if required. + String basePathId = sanitizeName(op.path.replace("/", "_").replace("{", "").replace("}", "").replaceAll("^_", "")).toUpperCase(); + String pathId = basePathId; + int pathIdTiebreaker = 2; + boolean found = false; + while (pathSetMap.containsKey(pathId)) { + Map pathSetEntry = pathSetMap.get(pathId); + if (pathSetEntry.get("path").equals(op.path)) { + found = true; + break; + } + pathId = basePathId + pathIdTiebreaker; + pathIdTiebreaker++; + } + + // Save off the regular expression and path details in the + // "pathSetMap", which we'll add to the source document that will be + // processed by the templates. + if (!found) { + Map pathSetEntry = new HashMap(); + pathSetEntry.put("path", op.path); + pathSetEntry.put("PATH_ID", pathId); + if (!op.pathParams.isEmpty()) { + pathSetEntry.put("hasPathParams", "true"); + } + // Don't prefix with '^' so that the templates can put the + // basePath on the front. + pathSetEntry.put("pathRegEx", op.path.replace("{", "(?P<").replace("}", ">[^/?#]*)") + "$"); + pathSetMap.put(pathId, pathSetEntry); + } + op.vendorExtensions.put("operation_id", underscore(op.operationId)); op.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase()); op.vendorExtensions.put("path", op.path.replace("{", ":").replace("}", "")); + op.vendorExtensions.put("PATH_ID", pathId); + op.vendorExtensions.put("hasPathParams", !op.pathParams.isEmpty()); op.vendorExtensions.put("HttpMethod", Character.toUpperCase(op.httpMethod.charAt(0)) + op.httpMethod.substring(1).toLowerCase()); - op.vendorExtensions.put("httpmethod", op.httpMethod.toLowerCase()); for (CodegenParameter param : op.allParams) { - String example = null; - - if (param.isString) { - if (param.dataFormat != null && param.dataFormat.equals("byte")) { - param.vendorExtensions.put("formatString", "\\\"{:?}\\\""); - example = "swagger::ByteArray(\"" + ((param.example != null) ? param.example : "") + "\".to_string().into_bytes())"; - } else { - param.vendorExtensions.put("formatString", "\\\"{}\\\""); - example = "\"" + ((param.example != null) ? param.example : "") + "\".to_string()"; - } - } else if (param.isPrimitiveType) { - if ((param.isByteArray) || - (param.isBinary)) { - // Binary primitive types don't implement `Display`. - param.vendorExtensions.put("formatString", "{:?}"); - example = "swagger::ByteArray(Vec::from(\"" + ((param.example != null) ? param.example : "") + "\"))"; - } else { - param.vendorExtensions.put("formatString", "{}"); - example = (param.example != null) ? param.example : ""; - } - } else if (param.isListContainer) { - param.vendorExtensions.put("formatString", "{:?}"); - example = (param.example != null) ? param.example : "&Vec::new()"; - } else if (param.isFile) { - param.vendorExtensions.put("formatString", "{:?}"); - op.vendorExtensions.put("hasFile", true); - additionalProperties.put("apiHasFile", true); - example = "Box::new(stream::once(Ok(b\"hello\".to_vec()))) as Box + Send>"; - } else { - param.vendorExtensions.put("formatString", "{:?}"); - if (param.example != null) { - example = "serde_json::from_str::<" + param.dataType + ">(\"" + param.example + "\").expect(\"Failed to parse JSON example\")"; - } - } - - if (param.required) { - if (example != null) { - param.vendorExtensions.put("example", example); - } else if (param.isListContainer) { - // Use the empty list if we don't have an example - param.vendorExtensions.put("example", "&Vec::new()"); - } - else { - // If we don't have an example that we can provide, we need to disable the client example, as it won't build. - param.vendorExtensions.put("example", "???"); - op.vendorExtensions.put("noClientExample", Boolean.TRUE); - } - } else if ((param.dataFormat != null)&&((param.dataFormat.equals("date-time")) || (param.dataFormat.equals("date")))) { - param.vendorExtensions.put("formatString", "{:?}"); - param.vendorExtensions.put("example", "None"); - } else { - // Not required, so override the format string and example - param.vendorExtensions.put("formatString", "{:?}"); - if (param.isFile) { - // Optional file types are wrapped in a future - param.vendorExtensions.put("example", (example != null) ? "Box::new(future::ok(Some(" + example + "))) as Box + Send>" : "None"); - } else { - param.vendorExtensions.put("example", (example != null) ? "Some(" + example + ")" : "None"); - } - } + processParam(param, op); } List consumes = new ArrayList(); - if (operation.getConsumes() != null) { - if (operation.getConsumes().size() > 0) { + + /* comment out the following logic as there's no consume in operation/global definition + if (consumes != null) { + if (!consumes.isEmpty()) { // use consumes defined in the operation consumes = operation.getConsumes(); } - } else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) { + } else if (openAPI != null && openAPI.getConsumes() != null && swagger.getConsumes().size() > 0) { // use consumes defined globally consumes = swagger.getConsumes(); LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); } + */ boolean consumesPlainText = false; boolean consumesXml = false; // if "consumes" is defined (per operation or using global definition) if (consumes != null && !consumes.isEmpty()) { + consumes.addAll(getConsumesInfo(operation)); List> c = new ArrayList>(); for (String mimeType : consumes) { Map mediaType = new HashMap(); @@ -544,6 +517,8 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation consumesXml = true; } else if (isMimetypePlainText(mimeType)) { consumesPlainText = true; + } else if (isMimetypeWwwFormUrlEncoded(mimeType)) { + additionalProperties.put("usesUrlEncodedForm", true); } mediaType.put("mediaType", mimeType); @@ -553,7 +528,10 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation op.hasConsumes = true; } - List produces = new ArrayList(); + + List produces = new ArrayList(getProducesInfo(operation)); + // if "consumes" is defined (per operation or using global definition) + /* if (operation.getProduces() != null) { if (operation.getProduces().size() > 0) { // use produces defined in the operation @@ -564,6 +542,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation produces = swagger.getProduces(); LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId); } + */ boolean producesXml = false; boolean producesPlainText = false; @@ -586,9 +565,10 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation op.hasProduces = true; } - if (op.bodyParam != null) { - if (paramHasXmlNamespace(op.bodyParam, definitions)){ + /* TODO move the following logic to postProcessOperations as there's no body/form parameter in OAS 3.0 + if (op.bodyParam != null) { + if (paramHasXmlNamespace(op.bodyParam, definitions)) { op.bodyParam.vendorExtensions.put("has_namespace", "true"); } for (String key : definitions.keySet()) { @@ -607,8 +587,9 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation } for (CodegenParameter param : op.bodyParams) { + processParam(param, op); - if (paramHasXmlNamespace(param, definitions)){ + if (paramHasXmlNamespace(param, definitions)) { param.vendorExtensions.put("has_namespace", "true"); } @@ -623,15 +604,28 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation param.vendorExtensions.put("consumesJson", true); } } + + for (CodegenParameter param : op.formParams) { + processParam(param, op); + } + */ + for (CodegenParameter param : op.headerParams) { + // If a header uses UUIDs, we need to import the UUID package. + if (param.dataType.equals("uuid::Uuid")) { + additionalProperties.put("apiUsesUuid", true); + } + processParam(param, op); + // Give header params a name in camel case. CodegenParameters don't have a nameInCamelCase property. param.vendorExtensions.put("typeName", toModelName(param.baseName)); } + for (CodegenResponse rsp : op.responses) { String[] words = rsp.message.split("[^A-Za-z ]"); String responseId; if (rsp.vendorExtensions.containsKey("x-responseId")) { - responseId = (String)rsp.vendorExtensions.get("x-responseId"); + responseId = (String) rsp.vendorExtensions.get("x-responseId"); } else if (words.length != 0) { responseId = camelize(words[0].replace(" ", "_")); } else { @@ -652,31 +646,29 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation rsp.vendorExtensions.put("producesJson", true); } + Schema response = (Schema) rsp.schema; // Check whether we're returning an object with a defined XML namespace. - Object property = rsp.schema; - if ((property != null) && (property instanceof RefProperty)){ - - RefProperty refProperty = (RefProperty) property; - String refName = refProperty.get$ref(); - if (refName.indexOf("#/definitions/") == 0) { - refName = refName.substring("#/definitions/".length()); - } - - Model model = definitions.get(refName); - - if ((model != null) && (model instanceof ModelImpl)) { - Xml xml = ((ModelImpl) model).getXml(); - if ((xml != null) && (xml.getNamespace() != null)){ + if (response != null && (!StringUtils.isEmpty(response.get$ref()))) { + Schema model = definitions.get(getSimpleRef(response.get$ref())); + if ((model != null)) { + XML xml = model.getXml(); + if ((xml != null) && (xml.getNamespace() != null)) { rsp.vendorExtensions.put("has_namespace", "true"); } } } } for (CodegenProperty header : rsp.headers) { + if (header.datatype.equals("uuid::Uuid")) { + additionalProperties.put("apiUsesUuid", true); + } header.nameInCamelCase = toModelName(header.baseName); } } for (CodegenProperty header : op.responseHeaders) { + if (header.datatype.equals("uuid::Uuid")) { + additionalProperties.put("apiUsesUuid", true); + } header.nameInCamelCase = toModelName(header.baseName); } @@ -689,42 +681,40 @@ public boolean isDataTypeFile(final String dataType) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); String innerType = getTypeDeclaration(inner); StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("array")).append("<"); - if (inner instanceof RefProperty) { + if (!StringUtils.isEmpty(inner.get$ref())) { typeDeclaration.append("models::"); } typeDeclaration.append(innerType).append(">"); return typeDeclaration.toString(); - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); String innerType = getTypeDeclaration(inner); StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("map")).append("<").append(typeMapping.get("string")).append(", "); - if (inner instanceof RefProperty) { + if (!StringUtils.isEmpty(inner.get$ref())) { typeDeclaration.append("models::"); } typeDeclaration.append(innerType).append(">"); return typeDeclaration.toString(); - } else if (p instanceof RefProperty) { + } else if (!StringUtils.isEmpty(p.get$ref())) { String datatype; try { - RefProperty r = (RefProperty) p; - datatype = r.get$ref(); + datatype = p.get$ref(); if (datatype.indexOf("#/definitions/") == 0) { datatype = toModelName(datatype.substring("#/definitions/".length())); } } catch (Exception e) { - LOGGER.warn("Error obtaining the datatype from RefProperty:" + p + ". Datatype default to Object"); + LOGGER.warn("Error obtaining the datatype from schema (model):" + p + ". Datatype default to Object"); datatype = "Object"; LOGGER.error(e.getMessage(), e); } return datatype; - } else if (p instanceof FileProperty) { + } else if (p instanceof FileSchema) { return typeMapping.get("File").toString(); } return super.getTypeDeclaration(p); @@ -733,7 +723,8 @@ public String getTypeDeclaration(Property p) { @Override public CodegenParameter fromParameter(Parameter param, Set imports) { CodegenParameter parameter = super.fromParameter(param, imports); - if(param instanceof BodyParameter) { + /* TODO need ot revise the logic below as there's no body parameter + if (param instanceof BodyParameter) { BodyParameter bp = (BodyParameter) param; Model model = bp.getSchema(); if (model instanceof RefModel) { @@ -756,50 +747,53 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { parameter.vendorExtensions.put("refName", ((ModelImpl) model).getName()); } } + */ return parameter; } @Override - public CodegenProperty fromProperty(String name, Property p) { + public CodegenProperty fromProperty(String name, Schema p) { CodegenProperty property = super.fromProperty(name, p); + + /* need to revise the logic below. Is this for alias? if (p instanceof RefProperty) { property.datatype = "models::" + property.datatype; } + */ return property; } @Override - public String toInstantiationType(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return instantiationTypes.get("array") + "<" + getSwaggerType(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return instantiationTypes.get("map") + "<" + typeMapping.get("string") + ", " + getSwaggerType(inner) + ">"; + public String toInstantiationType(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return instantiationTypes.get("array") + "<" + getSchemaType(inner) + ">"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return instantiationTypes.get("map") + "<" + typeMapping.get("string") + ", " + getSchemaType(inner) + ">"; } else { return null; } } @Override - public CodegenModel fromModel(String name, Model model) { - return fromModel(name, model, null); + public CodegenModel fromModel(String name, Schema schema) { + return fromModel(name, schema, null); } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel mdl = super.fromModel(name, model, allDefinitions); mdl.vendorExtensions.put("upperCaseName", name.toUpperCase()); - if (model instanceof ModelImpl) { - ModelImpl modelImpl = (ModelImpl) model; - mdl.dataType = typeMapping.get(modelImpl.getType()); + if (!StringUtils.isEmpty(model.get$ref())) { + Schema schema = allDefinitions.get(getSimpleRef(model.get$ref())); + mdl.dataType = typeMapping.get(schema.getType()); } - if (model instanceof ArrayModel) { - ArrayModel am = (ArrayModel) model; + if (ModelUtils.isArraySchema(model)) { + ArraySchema am = (ArraySchema) model; if ((am.getItems() != null) && - (am.getItems().getXml() != null)){ + (am.getItems().getXml() != null)) { // If this model's items require wrapping in xml, squirrel // away the xml name so we can insert it into the relevant model fields. @@ -820,7 +814,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe } @Override - public Map postProcessAllModels(Map objs){ + public Map postProcessAllModels(Map objs) { Map newObjs = super.postProcessAllModels(objs); //Index all CodegenModels by model name. @@ -835,13 +829,13 @@ public Map postProcessAllModels(Map objs){ } } - for (Entry entry : allModels.entrySet()){ + for (Entry entry : allModels.entrySet()) { String modelName = entry.getKey(); CodegenModel model = entry.getValue(); - for(CodegenProperty prop : model.vars){ + for (CodegenProperty prop : model.vars) { String xmlName = modelXmlNames.get(prop.datatype); - if (xmlName != null){ + if (xmlName != null) { prop.vendorExtensions.put("itemXmlName", xmlName); } } @@ -852,51 +846,51 @@ public Map postProcessAllModels(Map objs){ @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { - try { - objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); + generateYAMLSpecFile(objs); + + // We previously built a mapping from path to path ID and regular + // expression - see fromOperation for details. Sort it and add an + // index, and then add it to the objects that we're about to pass to + // the templates to process. + List>> pathSetEntryList = new ArrayList(pathSetMap.entrySet()); + Collections.sort(pathSetEntryList, new Comparator>>() { + public int compare(Map.Entry> a, Map.Entry> b) { + return a.getValue().get("path").compareTo(b.getValue().get("path")); } + }); + List pathSet = new ArrayList>(); + int index = 0; + for (Map.Entry> pathSetEntry : pathSetEntryList) { + Map pathSetEntryValue = pathSetEntry.getValue(); + pathSetEntryValue.put("index", Integer.toString(index)); + index++; + pathSet.add(pathSetEntryValue); } + objs.put("pathSet", pathSet); + return super.postProcessSupportingFileData(objs); } @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - return "\"" + dp.getDefault() + "\".to_string()"; - } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getDefault() != null) { - if (dp.getDefault().toString().equalsIgnoreCase("false")) + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + if (p.getDefault().toString().equalsIgnoreCase("false")) return "false"; else return "true"; } - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return "\"" + (String) p.getDefault() + "\".to_string()"; } } @@ -906,9 +900,9 @@ public String toDefaultValue(Property p) { @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); - if(!languageSpecificPrimitives.contains(property.datatype)) { + if (!languageSpecificPrimitives.contains(property.datatype)) { // If we use a more qualified model name, then only camelize the actual type, not the qualifier. - if(property.datatype.contains(":")) { + if (property.datatype.contains(":")) { int position = property.datatype.lastIndexOf(":"); property.datatype = property.datatype.substring(0, position) + camelize(property.datatype.substring(position)); } else { @@ -925,7 +919,7 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } else { // match int type to schema constraints - Long inclusiveMinimum = property.minimum != null ? Long.parseLong(property.minimum): null; + Long inclusiveMinimum = property.minimum != null ? Long.parseLong(property.minimum) : null; if (inclusiveMinimum != null && property.exclusiveMinimum) { inclusiveMinimum++; } @@ -933,7 +927,7 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert // a signed int is required unless a minimum greater than zero is set boolean unsigned = inclusiveMinimum != null && inclusiveMinimum >= 0; - Long inclusiveMaximum = property.maximum != null ? Long.parseLong(property.maximum): null; + Long inclusiveMaximum = property.maximum != null ? Long.parseLong(property.maximum) : null; if (inclusiveMaximum != null && property.exclusiveMaximum) { inclusiveMaximum--; } @@ -1013,15 +1007,15 @@ public Map postProcessModels(Map objs) { } - private boolean paramHasXmlNamespace(CodegenParameter param, Map definitions){ + private boolean paramHasXmlNamespace(CodegenParameter param, Map definitions) { Object refName = param.vendorExtensions.get("refName"); if ((refName != null) && (refName instanceof String)) { String name = (String) refName; - Model model = definitions.get(name); + Schema model = definitions.get(getSimpleRef(name)); - if ((model != null) && (model instanceof ModelImpl)) { - Xml xml = ((ModelImpl) model).getXml(); + if (model != null) { + XML xml = model.getXml(); if ((xml != null) && (xml.getNamespace() != null)) { return true; } @@ -1029,4 +1023,66 @@ private boolean paramHasXmlNamespace(CodegenParameter param, Map } return false; } + + private void processParam(CodegenParameter param, CodegenOperation op) { + String example = null; + + if (param.isString) { + if (param.dataFormat != null && param.dataFormat.equals("byte")) { + param.vendorExtensions.put("formatString", "\\\"{:?}\\\""); + example = "swagger::ByteArray(\"" + ((param.example != null) ? param.example : "") + "\".to_string().into_bytes())"; + } else { + param.vendorExtensions.put("formatString", "\\\"{}\\\""); + example = "\"" + ((param.example != null) ? param.example : "") + "\".to_string()"; + } + } else if (param.isPrimitiveType) { + if ((param.isByteArray) || + (param.isBinary)) { + // Binary primitive types don't implement `Display`. + param.vendorExtensions.put("formatString", "{:?}"); + example = "swagger::ByteArray(Vec::from(\"" + ((param.example != null) ? param.example : "") + "\"))"; + } else { + param.vendorExtensions.put("formatString", "{}"); + example = (param.example != null) ? param.example : ""; + } + } else if (param.isListContainer) { + param.vendorExtensions.put("formatString", "{:?}"); + example = (param.example != null) ? param.example : "&Vec::new()"; + } else if (param.isFile) { + param.vendorExtensions.put("formatString", "{:?}"); + op.vendorExtensions.put("hasFile", true); + additionalProperties.put("apiHasFile", true); + example = "Box::new(stream::once(Ok(b\"hello\".to_vec()))) as Box + Send>"; + } else { + param.vendorExtensions.put("formatString", "{:?}"); + if (param.example != null) { + example = "serde_json::from_str::<" + param.dataType + ">(\"" + param.example + "\").expect(\"Failed to parse JSON example\")"; + } + } + + if (param.required) { + if (example != null) { + param.vendorExtensions.put("example", example); + } else if (param.isListContainer) { + // Use the empty list if we don't have an example + param.vendorExtensions.put("example", "&Vec::new()"); + } else { + // If we don't have an example that we can provide, we need to disable the client example, as it won't build. + param.vendorExtensions.put("example", "???"); + op.vendorExtensions.put("noClientExample", Boolean.TRUE); + } + } else if ((param.dataFormat != null) && ((param.dataFormat.equals("date-time")) || (param.dataFormat.equals("date")))) { + param.vendorExtensions.put("formatString", "{:?}"); + param.vendorExtensions.put("example", "None"); + } else { + // Not required, so override the format string and example + param.vendorExtensions.put("formatString", "{:?}"); + if (param.isFile) { + // Optional file types are wrapped in a future + param.vendorExtensions.put("example", (example != null) ? "Box::new(future::ok(Some(" + example + "))) as Box + Send>" : "None"); + } else { + param.vendorExtensions.put("example", (example != null) ? "Some(" + example + ")" : "None"); + } + } + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaClientCodegen.java index e336270b5eac..20dc744eaab5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaClientCodegen.java @@ -29,16 +29,16 @@ public ScalaClientCodegen() { setReservedWordsLowerCase( Arrays.asList( - // local variable names used in API methods (endpoints) - "path", "contentTypes", "contentType", "queryParams", "headerParams", - "formParams", "postBody", "mp", "basePath", "apiInvoker", - - // scala reserved words - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + // local variable names used in API methods (endpoints) + "path", "contentTypes", "contentType", "queryParams", "headerParams", + "formParams", "postBody", "mp", "basePath", "apiInvoker", + + // scala reserved words + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") ); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); @@ -63,12 +63,12 @@ public ScalaClientCodegen() { supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); // gradleWrapper files - supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew") ); - supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") ); - supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache", - gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") ); - supportingFiles.add(new SupportingFile( "gradle-wrapper.jar", - gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") ); + supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); + supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); + supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); + supportingFiles.add(new SupportingFile("gradle-wrapper.jar", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar")); supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); @@ -113,7 +113,7 @@ public void processOpts() { setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); } } - + public void setModelPropertyNaming(String naming) { if ("original".equals(naming) || "camelCase".equals(naming) || "PascalCase".equals(naming) || "snake_case".equals(naming)) { @@ -128,27 +128,28 @@ public void setModelPropertyNaming(String naming) { public String getModelPropertyNaming() { return this.modelPropertyNaming; } + @Override public String toVarName(String name) { // sanitize name name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - if("_".equals(name)) { - name = "_u"; + + if ("_".equals(name)) { + name = "_u"; } - + // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { return name; } - + name = getNameUsingModelPropertyNaming(name); - + // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { name = escapeReservedWord(name); } - + return name; } @@ -160,13 +161,18 @@ public String toParamName(String name) { public 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); - default: throw new IllegalArgumentException("Invalid model property naming '" + - name + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); + case original: + return name; + case camelCase: + return camelize(name, true); + case PascalCase: + return camelize(name); + case snake_case: + return underscore(name); + default: + throw new IllegalArgumentException("Invalid model property naming '" + + name + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); } } @@ -204,25 +210,25 @@ public String toOperationId(String operationId) { @Override public String toModelName(final String name) { final String sanitizedName = sanitizeName(modelNamePrefix + this.stripPackageName(name) + modelNameSuffix); - + // camelize the model name // phone_number => PhoneNumber final String camelizedName = camelize(sanitizedName); - + // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { final String modelName = "Model" + camelizedName; LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); return modelName; } - + // model name starts with number if (name.matches("^\\d.*")) { final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); return modelName; } - + return camelizedName; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java index ca6b9ec2c191..4e39bb54d697 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java @@ -1,9 +1,13 @@ package org.openapitools.codegen.languages; import org.openapitools.codegen.*; -import io.swagger.models.*; -import io.swagger.models.parameters.*; -import io.swagger.models.properties.*; +import org.openapitools.codegen.utils.*; +import org.openapitools.codegen.mustache.*; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; @@ -24,7 +28,6 @@ public class ScalaGatlingCodegen extends AbstractScalaCodegen implements Codegen * Configures the type of generator. * * @return the CodegenType for this generator - * @see org.openapitools.codegen.CodegenType */ public CodegenType getTag() { return CodegenType.CLIENT; @@ -194,24 +197,24 @@ public String apiFileFolder() { } /** - * Modifies the swagger doc to make mustache easier to use + * Modifies the openapi doc to make mustache easier to use * - * @param swagger input swagger document + * @param openAPI input openapi document */ @Override - public void preprocessSwagger(Swagger swagger) { - for (String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if (path.getOperations() == null) { + public void preprocessOpenAPI(OpenAPI openAPI) { + for (String pathname : openAPI.getPaths().keySet()) { + PathItem path = openAPI.getPaths().get(pathname); + if (path.readOperations() == null) { continue; } - for (Operation operation : path.getOperations()) { - if (!operation.getVendorExtensions().keySet().contains("x-gatling-path")) { + for (Operation operation : path.readOperations()) { + if (!operation.getExtensions().keySet().contains("x-gatling-path")) { if (pathname.contains("{")) { String gatlingPath = pathname.replaceAll("\\{", "\\$\\{"); - operation.setVendorExtension("x-gatling-path", gatlingPath); + operation.addExtension("x-gatling-path", gatlingPath); } else { - operation.setVendorExtension("x-gatling-path", pathname); + operation.addExtension("x-gatling-path", pathname); } } @@ -220,19 +223,24 @@ public void preprocessSwagger(Swagger swagger) { Set queryParameters = new HashSet<>(); Set pathParameters = new HashSet<>(); - for (Parameter parameter : operation.getParameters()) { - if (parameter.getIn().equalsIgnoreCase("header")) { - headerParameters.add(parameter); - } + if (operation.getParameters() != null) { + + for (Parameter parameter : operation.getParameters()) { + if (parameter.getIn().equalsIgnoreCase("header")) { + headerParameters.add(parameter); + } + /* need to revise below as form parameter is no longer in the parameter list if (parameter.getIn().equalsIgnoreCase("formData")) { formParameters.add(parameter); } - if (parameter.getIn().equalsIgnoreCase("query")) { - queryParameters.add(parameter); - } - if (parameter.getIn().equalsIgnoreCase("path")) { - pathParameters.add(parameter); - } + */ + if (parameter.getIn().equalsIgnoreCase("query")) { + queryParameters.add(parameter); + } + if (parameter.getIn().equalsIgnoreCase("path")) { + pathParameters.add(parameter); + } + /* TODO need to revise below as body is no longer in the parameter if (parameter.getIn().equalsIgnoreCase("body")) { BodyParameter bodyParameter = (BodyParameter) parameter; Model model = bodyParameter.getSchema(); @@ -264,6 +272,8 @@ public void preprocessSwagger(Swagger swagger) { } } + */ + } } prepareGatlingData(operation, headerParameters, "header"); @@ -276,7 +286,7 @@ public void preprocessSwagger(Swagger swagger) { } /** - * Creates all the necessary swagger vendor extensions and feeder files for gatling + * Creates all the necessary openapi vendor extensions and feeder files for gatling * * @param operation Swagger Operation * @param parameters Swagger Parameters @@ -293,8 +303,8 @@ private void prepareGatlingData(Operation operation, Set parameters, vendorList.add(extensionMap); parameterNames.add(parameter.getName()); } - operation.setVendorExtension("x-gatling-" + parameterType.toLowerCase() + "-params", vendorList); - operation.setVendorExtension("x-gatling-" + parameterType.toLowerCase() + "-feeder", operation.getOperationId() + parameterType.toUpperCase() + "Feeder"); + operation.addExtension("x-gatling-" + parameterType.toLowerCase() + "-params", vendorList); + operation.addExtension("x-gatling-" + parameterType.toLowerCase() + "-feeder", operation.getOperationId() + parameterType.toUpperCase() + "Feeder"); try { FileUtils.writeStringToFile(new File(outputFolder + File.separator + dataFolder + File.separator + operation.getOperationId() + "-" + parameterType.toLowerCase() + "Params.csv"), StringUtils.join(parameterNames, ",")); } catch (IOException ioe) { @@ -310,36 +320,34 @@ private void prepareGatlingData(Operation operation, Set parameters, * @return a string value used as the `dataType` field for model templates, `returnType` for api templates */ @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * Optional - openapi type conversion. This is used to map openapi types in a `Schema` into * either language specific types via `typeMapping` or into complex models if there is not a mapping. * * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property */ @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); if (languageSpecificPrimitives.contains(type)) return toModelName(type); } else - type = swaggerType; + type = schemaType; return toModelName(type); } } 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 0bf8c875e807..edbbbc23f23c 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 @@ -7,268 +7,268 @@ public class ScalaLagomServerCodegen extends AbstractScalaCodegen implements CodegenConfig { - private String authScheme = ""; - private boolean authPreemptive=false; - protected String groupId = "io.swagger"; - protected String artifactId = "scala-lagom-server"; - protected String artifactVersion = "1.0.0"; - - public ScalaLagomServerCodegen() { - super(); - outputFolder = "generated-code/scala-lagom-server"; - modelTemplateFiles.put("model.mustache", ".scala"); - apiTemplateFiles.put("api.mustache", ".scala"); - embeddedTemplateDir = templateDir = "scala-lagom-server"; - apiPackage = "io.swagger.client.api"; - modelPackage = "io.swagger.client.model"; - - setReservedWordsLowerCase( - Arrays.asList( - // local variable names used in API methods (endpoints) - "path", "contentTypes", "contentType", "queryParams", "headerParams", - "formParams", "postBody", "mp", "basePath", "apiInvoker", - - // scala reserved words - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") - ); - - additionalProperties.put(CodegenConstants.GROUP_ID, groupId); - additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); - additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); - additionalProperties.put("authScheme", authScheme); - additionalProperties.put("authPreemptive", authPreemptive); - - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); - supportingFiles.add(new SupportingFile("build.properties.mustache", "", "project/build.properties")); - supportingFiles.add(new SupportingFile("plugins.sbt.mustache", "", "project/plugins.sbt")); - - importMapping.remove("List"); - importMapping.remove("Set"); - importMapping.remove("Map"); - - importMapping.put("DateTime", "org.joda.time.DateTime"); - importMapping.put("ListBuffer", "scala.collection.mutable.ListBuffer"); - - typeMapping = new HashMap(); - typeMapping.put("Integer", "Int"); - typeMapping.put("enum", "NSString"); - typeMapping.put("array", "Seq"); - typeMapping.put("set", "Set"); - typeMapping.put("boolean", "Boolean"); - typeMapping.put("string", "String"); - typeMapping.put("int", "Int"); - typeMapping.put("long", "Long"); - typeMapping.put("float", "Float"); - typeMapping.put("byte", "Byte"); - typeMapping.put("short", "Short"); - typeMapping.put("char", "Char"); - typeMapping.put("long", "Long"); - typeMapping.put("double", "Double"); - typeMapping.put("object", "Any"); - typeMapping.put("file", "File"); - - //TODO binary should be mapped to byte array - // mapped to String as a workaround - typeMapping.put("binary", "String"); - typeMapping.put("ByteArray", "String"); - - instantiationTypes.put("array", "ListBuffer"); - instantiationTypes.put("map", "HashMap"); - - cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, - CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); - } - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { - setModelPropertyNaming( - (String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); + private String authScheme = ""; + private boolean authPreemptive = false; + protected String groupId = "io.swagger"; + protected String artifactId = "scala-lagom-server"; + protected String artifactVersion = "1.0.0"; + + public ScalaLagomServerCodegen() { + super(); + outputFolder = "generated-code/scala-lagom-server"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + embeddedTemplateDir = templateDir = "scala-lagom-server"; + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.model"; + + setReservedWordsLowerCase( + Arrays.asList( + // local variable names used in API methods (endpoints) + "path", "contentTypes", "contentType", "queryParams", "headerParams", + "formParams", "postBody", "mp", "basePath", "apiInvoker", + + // scala reserved words + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + ); + + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + additionalProperties.put("authScheme", authScheme); + additionalProperties.put("authPreemptive", authPreemptive); + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); + supportingFiles.add(new SupportingFile("build.properties.mustache", "", "project/build.properties")); + supportingFiles.add(new SupportingFile("plugins.sbt.mustache", "", "project/plugins.sbt")); + + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + importMapping.put("DateTime", "org.joda.time.DateTime"); + importMapping.put("ListBuffer", "scala.collection.mutable.ListBuffer"); + + typeMapping = new HashMap(); + typeMapping.put("Integer", "Int"); + typeMapping.put("enum", "NSString"); + typeMapping.put("array", "Seq"); + typeMapping.put("set", "Set"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Int"); + typeMapping.put("long", "Long"); + typeMapping.put("float", "Float"); + typeMapping.put("byte", "Byte"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "Char"); + typeMapping.put("long", "Long"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Any"); + typeMapping.put("file", "File"); + + //TODO binary should be mapped to byte array + // mapped to String as a workaround + typeMapping.put("binary", "String"); + typeMapping.put("ByteArray", "String"); + + instantiationTypes.put("array", "ListBuffer"); + instantiationTypes.put("map", "HashMap"); + + cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, + CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); } - } - - public void setModelPropertyNaming(String naming) { - if ("original".equals(naming) || "camelCase".equals(naming) || - "PascalCase".equals(naming) || "snake_case".equals(naming)) { - this.modelPropertyNaming = naming; - } else { - throw new IllegalArgumentException("Invalid model property naming '" + - naming + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); - } - } - public String getModelPropertyNaming() { - return this.modelPropertyNaming; - } + @Override + public void processOpts() { + super.processOpts(); - @Override - public String toVarName(String name) { - // sanitize name - name = sanitizeName( - name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { + setModelPropertyNaming( + (String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); + } + } - if ("_".equals(name)) { - name = "_u"; + public void setModelPropertyNaming(String naming) { + if ("original".equals(naming) || "camelCase".equals(naming) || + "PascalCase".equals(naming) || "snake_case".equals(naming)) { + this.modelPropertyNaming = naming; + } else { + throw new IllegalArgumentException("Invalid model property naming '" + + naming + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } } - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) { - return name; + public String getModelPropertyNaming() { + return this.modelPropertyNaming; } - name = getNameUsingModelPropertyNaming(name); + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName( + name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - // for reserved word or word starting with number, append _ - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } + if ("_".equals(name)) { + name = "_u"; + } - return name; - } + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } + name = getNameUsingModelPropertyNaming(name); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } - 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); - default: - throw new IllegalArgumentException("Invalid model property naming '" + - name + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); } - } - - @Override - public CodegenType getTag() { - return CodegenType.SERVER; - } + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } - @Override - public String getName() { - return "scala-lagom-server"; - } + 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); + default: + throw new IllegalArgumentException("Invalid model property naming '" + + name + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } - @Override - public String getHelp() { - return "Generates a Lagom API (Beta) in scala"; - } + } - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method name (operationId) not allowed"); + @Override + public CodegenType getTag() { + return CodegenType.SERVER; } - // method name cannot use reserved keyword, e.g. return - if (isReservedWord(operationId)) { - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + @Override + public String getName() { + return "scala-lagom-server"; } - return camelize(operationId, true); - } + @Override + public String getHelp() { + return "Generates a Lagom API server (Beta) in scala"; + } - @Override - public String toModelName(final String name) { - final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix); + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } - // camelize the model name - // phone_number => PhoneNumber - final String camelizedName = camelize(sanitizedName); + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(camelizedName)) { - final String modelName = "Model" + camelizedName; - LOGGER.warn( - camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); - return modelName; + return camelize(operationId, true); } - // model name starts with number - if (name.matches("^\\d.*")) { - final String modelName = - "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn( - name + " (model name starts with number) cannot be used as model name. Renamed to " - + modelName); - return modelName; - } + @Override + public String toModelName(final String name) { + final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix); - return camelizedName; - } - - @Override - public Map postProcessModelsEnum(Map objs) { - objs = super.postProcessModelsEnum(objs); - List models = (List) objs.get("models"); - for (Object _mo : models) { - Map mo = (Map) _mo; - CodegenModel cm = (CodegenModel) mo.get("model"); - - for (CodegenProperty var : cm.vars) { - if (var.isEnum) { - List enumValues = (List) var.allowableValues.get("values"); - - for (final ListIterator i = enumValues.listIterator(); i.hasNext(); ) { - final String element = String.valueOf(i.next()); - i.set(element.replaceAll("^\"|\"$", "")); - } + // camelize the model name + // phone_number => PhoneNumber + final String camelizedName = camelize(sanitizedName); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(camelizedName)) { + final String modelName = "Model" + camelizedName; + LOGGER.warn( + camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); + return modelName; } - } - } - //Needed import for Gson based libraries - if (additionalProperties.containsKey("gson")) { - List> imports = (List>) objs.get("imports"); - - for (Object _mo : models) { - Map mo = (Map) _mo; - CodegenModel cm = (CodegenModel) mo.get("model"); - // for enum model - if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) { - cm.imports.add(importMapping.get("SerializedName")); - Map item = new HashMap(); - item.put("import", importMapping.get("SerializedName")); - imports.add(item); + // model name starts with number + if (name.matches("^\\d.*")) { + final String modelName = + "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) + LOGGER.warn( + name + " (model name starts with number) cannot be used as model name. Renamed to " + + modelName); + return modelName; } - } + + return camelizedName; } - return objs; - } + @Override + public Map postProcessModelsEnum(Map objs) { + objs = super.postProcessModelsEnum(objs); + List models = (List) objs.get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + + for (CodegenProperty var : cm.vars) { + if (var.isEnum) { + List enumValues = (List) var.allowableValues.get("values"); + + for (final ListIterator i = enumValues.listIterator(); i.hasNext(); ) { + final String element = String.valueOf(i.next()); + i.set(element.replaceAll("^\"|\"$", "")); + } + } + } + } + + //Needed import for Gson based libraries + if (additionalProperties.containsKey("gson")) { + List> imports = (List>) objs.get("imports"); + + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + // for enum model + if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) { + cm.imports.add(importMapping.get("SerializedName")); + Map item = new HashMap(); + item.put("import", importMapping.get("SerializedName")); + imports.add(item); + } + } + } - @Override - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - ArrayList oplist = (ArrayList) operations.get("operation"); + return objs; + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + ArrayList oplist = (ArrayList) operations.get("operation"); - for (CodegenOperation codegenOperation : oplist) { - String path = codegenOperation.path; - codegenOperation.path = path.replaceAll("\\{", ":").replaceAll("}", ""); + for (CodegenOperation codegenOperation : oplist) { + String path = codegenOperation.path; + codegenOperation.path = path.replaceAll("\\{", ":").replaceAll("}", ""); + } + return objs; } - return objs; - } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalatraServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalatraServerCodegen.java index fb5c08bfd194..6384b3bbc60e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalatraServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalatraServerCodegen.java @@ -1,11 +1,13 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.*; +import org.openapitools.codegen.mustache.*; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; import java.util.Arrays; import java.util.HashMap; @@ -129,7 +131,7 @@ public Map postProcessOperations(Map objs) { for (CodegenOperation op : operationList) { // force http method to lower case op.httpMethod = op.httpMethod.toLowerCase(); - + String[] items = op.path.split("/", -1); String scalaPath = ""; int pathParamIndex = 0; @@ -142,7 +144,7 @@ public Map postProcessOperations(Map objs) { scalaPath = scalaPath + items[i]; } - if (i != items.length -1) { + if (i != items.length - 1) { scalaPath = scalaPath + "/"; } } 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 54ad796ac3bb..e6be1fcd2a04 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 @@ -5,19 +5,13 @@ import com.samskivert.mustache.Template; import org.openapitools.codegen.*; - -import io.swagger.models.auth.SecuritySchemeDefinition; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; +import org.openapitools.codegen.utils.*; +import org.openapitools.codegen.mustache.*; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; import java.io.File; import java.io.IOException; @@ -34,27 +28,27 @@ public class ScalazClientCodegen extends AbstractScalaCodegen implements Codegen public ScalazClientCodegen() { super(); - outputFolder = "generated-code/scalaz"; + outputFolder = "generated-code/scalaz"; embeddedTemplateDir = templateDir = "scalaz"; - apiPackage = "io.swagger.client.api"; - modelPackage = "io.swagger.client.api"; + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.api"; modelTemplateFiles.put("model.mustache", ".scala"); apiTemplateFiles.put("api.mustache", ".scala"); setReservedWordsLowerCase( - Arrays.asList( - // local variable names used in API methods (endpoints) - "path", "contentTypes", "contentType", "queryParams", "headerParams", - "formParams", "postBody", "mp", "basePath", "apiInvoker", - - // scala reserved words - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") - ); + Arrays.asList( + // local variable names used in API methods (endpoints) + "path", "contentTypes", "contentType", "queryParams", "headerParams", + "formParams", "postBody", "mp", "basePath", "apiInvoker", + + // scala reserved words + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + ); additionalProperties.put("apiPackage", apiPackage); @@ -106,42 +100,43 @@ public void processOpts() { setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); } } - + public void setModelPropertyNaming(String naming) { if ("original".equals(naming) || "camelCase".equals(naming) || - "PascalCase".equals(naming) || "snake_case".equals(naming)) { + "PascalCase".equals(naming) || "snake_case".equals(naming)) { this.modelPropertyNaming = naming; } else { throw new IllegalArgumentException("Invalid model property naming '" + - naming + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); + naming + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); } } public String getModelPropertyNaming() { return this.modelPropertyNaming; } + @Override public String toVarName(String name) { // sanitize name name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - if("_".equals(name)) { + + if ("_".equals(name)) { name = "_u"; } - + // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { return name; } - + name = getNameUsingModelPropertyNaming(name); - + // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { name = escapeReservedWord(name); } - + return name; } @@ -158,13 +153,18 @@ public String toEnumName(CodegenProperty property) { public 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); - default: throw new IllegalArgumentException("Invalid model property naming '" + - name + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); + case original: + return name; + case camelCase: + return camelize(name, true); + case PascalCase: + return camelize(name); + case snake_case: + return underscore(name); + default: + throw new IllegalArgumentException("Invalid model property naming '" + + name + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); } } @@ -202,25 +202,25 @@ public String toOperationId(String operationId) { @Override public String toModelName(final String name) { final String sanitizedName = sanitizeName(modelNamePrefix + this.stripPackageName(name) + modelNameSuffix); - + // camelize the model name // phone_number => PhoneNumber final String camelizedName = camelize(sanitizedName); - + // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { final String modelName = "Model" + camelizedName; LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); return modelName; } - + // model name starts with number if (name.matches("^\\d.*")) { final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); return modelName; } - + return camelizedName; } 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 c73d4cbab0df..fd665e9e1022 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 @@ -2,20 +2,20 @@ import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; + import org.openapitools.codegen.*; import org.openapitools.codegen.languages.features.BeanValidationFeatures; import org.openapitools.codegen.languages.features.OptionalFeatures; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.Swagger; +import org.openapitools.codegen.utils.URLPathUtils; +import io.swagger.v3.oas.models.*; +import java.net.URL; import java.io.File; import java.io.IOException; import java.io.Writer; import java.util.*; import java.util.regex.Matcher; - public class SpringCodegen extends AbstractJavaCodegen implements BeanValidationFeatures, OptionalFeatures { public static final String DEFAULT_LIBRARY = "spring-boot"; @@ -371,15 +371,17 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera } @Override - public void preprocessSwagger(Swagger swagger) { - super.preprocessSwagger(swagger); + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); + /* TODO the following logic should not need anymore in OAS 3.0 if ("/".equals(swagger.getBasePath())) { swagger.setBasePath(""); } + */ if(!additionalProperties.containsKey(TITLE)) { // From the title, compute a reasonable name for the package and the API - String title = swagger.getInfo().getTitle(); + String title = openAPI.getInfo().getTitle(); // Drop any API suffix if (title != null) { @@ -393,21 +395,18 @@ public void preprocessSwagger(Swagger swagger) { additionalProperties.put(TITLE, this.title); } - String host = swagger.getHost(); - String port = "8080"; - if (host != null) { - String[] parts = host.split(":"); - if (parts.length > 1) { - port = parts[1]; - } + URL url = URLPathUtils.getServerURL(openAPI); + Integer port = 8080; + if (url.getPort() != 0) { + port = url.getPort(); } - this.additionalProperties.put("serverPort", port); - if (swagger.getPaths() != null) { - for (String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if (path.getOperations() != null) { - for (Operation operation : path.getOperations()) { + + if (openAPI.getPaths() != null) { + for (String pathname : openAPI.getPaths().keySet()) { + PathItem path = openAPI.getPaths().get(pathname); + if (path.readOperations() != null) { + for (Operation operation : path.readOperations()) { if (operation.getTags() != null) { List> tags = new ArrayList>(); for (String tag : operation.getTags()) { @@ -423,7 +422,7 @@ public void preprocessSwagger(Swagger swagger) { String tag = operation.getTags().get(0); operation.setTags(Arrays.asList(tag)); } - operation.setVendorExtension("x-tags", tags); + operation.addExtension("x-tags", tags); } } } 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 d94745b4b531..193197382451 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 @@ -1,16 +1,24 @@ package org.openapitools.codegen.languages; import com.samskivert.mustache.Mustache; -import org.openapitools.codegen.*; -import io.swagger.models.Info; -import org.yaml.snakeyaml.error.Mark; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenResponse; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.SupportingFile; import org.openapitools.codegen.utils.Markdown; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; import org.apache.commons.lang3.StringUtils; @@ -97,16 +105,14 @@ public String getHelp() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } @@ -128,11 +134,11 @@ public Map postProcessOperations(Map objs) { } @Override - public void preprocessSwagger(Swagger swagger) { - super.preprocessSwagger(swagger); + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); - if (swagger.getInfo() != null) { - Info info = swagger.getInfo(); + if (openAPI.getInfo() != null) { + 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())); @@ -150,12 +156,12 @@ public void preprocessSwagger(Swagger swagger) { additionalProperties.put("jsProjectName", jsProjectName); additionalProperties.put("jsModuleName", jsModuleName); - preparHtmlForGlobalDescription(swagger); + preparHtmlForGlobalDescription(openAPI); } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, OpenAPI openAPI) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, openAPI); if (op.returnType != null) { op.returnType = normalizeType(op.returnType); } @@ -199,13 +205,17 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation * @param swagger The base object containing the global description through "Info" class * @return Void */ - private void preparHtmlForGlobalDescription(Swagger swagger) { - String currentDescription = swagger.getInfo().getDescription(); + private void preparHtmlForGlobalDescription(OpenAPI openAPI) { + if (openAPI.getInfo() == null) { + return; + } + + String currentDescription = openAPI.getInfo().getDescription(); if (currentDescription != null && !currentDescription.isEmpty()) { Markdown markInstance = new Markdown(); - swagger.getInfo().setDescription( markInstance.toHtml(currentDescription) ); + openAPI.getInfo().setDescription( markInstance.toHtml(currentDescription) ); } else { - LOGGER.error("Swagger object description is empty [" + swagger.getInfo().getTitle() + "]"); + LOGGER.error("OpenAPI object description is empty [" + openAPI.getInfo().getTitle() + "]"); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtmlGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtmlGenerator.java index cbb8deff8d73..35f1eb15b48a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtmlGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtmlGenerator.java @@ -11,13 +11,14 @@ import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.SupportingFile; -import io.swagger.models.Info; -import io.swagger.models.Model; -import io.swagger.models.Swagger; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; import org.openapitools.codegen.utils.Markdown; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.info.Info; + import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -26,8 +27,6 @@ import com.samskivert.mustache.Escapers; import com.samskivert.mustache.Mustache.Compiler; -import org.openapitools.codegen.utils.Markdown; - public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; @@ -70,19 +69,17 @@ public StaticHtmlGenerator() { importMapping = new HashMap(); } - - /** * Convert Markdown (CommonMark) to HTML. This class also disables normal HTML - * escaping in the Mustache engine (see {@link DefaultCodegen#processCompiler(Compiler)} above.) + * escaping in the Mustache engine. */ - @Override + @Override public String escapeText(String input) { // newline escaping disabled for HTML documentation for markdown to work correctly return toHtml(input); } - @Override + @Override public CodegenType getTag() { return CodegenType.DOCUMENTATION; } @@ -98,21 +95,19 @@ public String getHelp() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); + return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } -@Override + @Override public Map postProcessOperations(Map objs) { Map operations = (Map) objs.get("operations"); List operationList = (List) operations.get("operation"); @@ -140,7 +135,7 @@ public String escapeUnsafeCharacters(String input) { return input; } - /** + /** * Markdown conversion emits HTML and by default, the Mustache * {@link Compiler} will escape HTML. For example a summary * "Text with **bold**" is converted from Markdown to HTML as @@ -161,6 +156,7 @@ public Compiler processCompiler(Compiler compiler) { /** * Convert Markdown text to HTML + * * @param input text in Markdown; may be null. * @return the text, converted to Markdown. For null input, "" is returned. */ @@ -178,12 +174,12 @@ public String toModelName(final String name) { return name; } - public void preprocessSwagger(Swagger swagger) { - Info info = swagger.getInfo(); + public void preprocessOpenAPI(OpenAPI openAPI) { + Info info = openAPI.getInfo(); info.setDescription(toHtml(info.getDescription())); info.setTitle(toHtml(info.getTitle())); - Map models = swagger.getDefinitions(); - for (Model model : models.values()) { + Map models = openAPI.getComponents().getSchemas(); + for (Schema model : models.values()) { model.setDescription(toHtml(model.getDescription())); model.setTitle(toHtml(model.getTitle())); } @@ -198,7 +194,7 @@ public void postProcessParameter(CodegenParameter parameter) { // override to post-process any model properties public void postProcessModelProperty(CodegenModel model, - CodegenProperty property) { + CodegenProperty property) { property.description = toHtml(property.description); property.unescapedDescription = toHtml( property.unescapedDescription); 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 649b9791f0ad..f11e275d0976 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 @@ -3,16 +3,18 @@ import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; + import org.openapitools.codegen.*; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.models.parameters.HeaderParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.utils.*; +import org.openapitools.codegen.mustache.*; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.core.util.Yaml; +import io.swagger.v3.parser.util.SchemaTypeUtil; + import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.text.WordUtils; @@ -52,31 +54,6 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { protected String[] responseAs = new String[0]; protected String sourceFolder = "Classes" + File.separator + "Swaggers"; - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - @Override - public String getName() { - return "swift3"; - } - - @Override - public String getHelp() { - return "Generates a swift client library."; - } - - @Override - protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { - - final Property additionalProperties = swaggerModel.getAdditionalProperties(); - - if(additionalProperties != null) { - codegenModel.additionalPropertiesType = getSwaggerType(additionalProperties); - } - } - public Swift3Codegen() { super(); outputFolder = "generated-code" + File.separator + "swift"; @@ -86,6 +63,9 @@ public Swift3Codegen() { apiPackage = File.separator + "APIs"; modelPackage = File.separator + "Models"; + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + languageSpecificPrimitives = new HashSet<>( Arrays.asList( "Int", @@ -116,18 +96,18 @@ public Swift3Codegen() { ); reservedWords = new HashSet<>( Arrays.asList( - // name used by swift client - "ErrorResponse", "Response", - - // swift keywords - "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL", - "class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", - "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", - "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", - "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", - "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", - "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", - "required", "right", "set", "Type", "unowned", "weak", "Data") + // name used by swift client + "ErrorResponse", "Response", + + // swift keywords + "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL", + "class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", + "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", + "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", + "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", + "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", + "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", + "required", "right", "set", "Type", "unowned", "weak", "Data") ); typeMapping = new HashMap<>(); @@ -173,23 +153,40 @@ public Swift3Codegen() { cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec")); cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec")); cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class of {{projectName}}API")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(LENIENT_TYPE_CAST, "Accept and cast values for simple types (string->bool, string->int, int->string)") .defaultValue(Boolean.FALSE.toString())); } @Override - public void processOpts() { - super.processOpts(); + public CodegenType getTag() { + return CodegenType.CLIENT; + } - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + @Override + public String getName() { + return "swift3"; + } + + @Override + public String getHelp() { + return "Generates a Swift 3.x client library."; + } + + @Override + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { + + final Schema additionalProperties = (Schema) schema.getAdditionalProperties(); + + if (additionalProperties != null) { + codegenModel.additionalPropertiesType = getSchemaType(additionalProperties); } + } + + @Override + public void processOpts() { + super.processOpts(); // Setup project name if (additionalProperties.containsKey(PROJECT_NAME)) { @@ -260,7 +257,7 @@ protected boolean isReservedWord(String word) { @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; // add an underscore to the name @@ -277,29 +274,28 @@ public String apiFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return "[String:" + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type) || defaultIncludes.contains(type)) return type; } else - type = swaggerType; + type = openAPIType; return toModelName(type); } @@ -365,20 +361,19 @@ public String toModelFilename(String name) { } @Override - public String toDefaultValue(Property p) { + public String toDefaultValue(Schema p) { // nil return null; } @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); + public String toInstantiationType(Schema p) { + if (ModelUtils.isMapSchema(p)) { + String inner = getSchemaType((Schema) p.getAdditionalProperties()); return inner; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); return "[" + inner + "]"; } return null; @@ -458,23 +453,23 @@ public String toParamName(String name) { } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { - CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); - if(codegenModel.description != null) { + public CodegenModel fromModel(String name, Schema schema, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, schema, allDefinitions); + if (codegenModel.description != null) { codegenModel.imports.add("ApiModel"); } if (allDefinitions != null) { - String parentSchema = codegenModel.parentSchema; + String parentSchema = codegenModel.parentSchema; - // multilevel inheritance: reconcile properties of all the parents - while (parentSchema != null) { - final Model parentModel = allDefinitions.get(parentSchema); - final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions); - codegenModel = Swift3Codegen.reconcileProperties(codegenModel, parentCodegenModel); + // multilevel inheritance: reconcile properties of all the parents + while (parentSchema != null) { + final Schema parentModel = allDefinitions.get(parentSchema); + final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions); + codegenModel = Swift3Codegen.reconcileProperties(codegenModel, parentCodegenModel); - // get the next parent - parentSchema = parentCodegenModel.parentSchema; - } + // get the next parent + parentSchema = parentCodegenModel.parentSchema; + } } return codegenModel; @@ -644,24 +639,24 @@ private static CodegenModel reconcileProperties(CodegenModel codegenModel, Codeg boolean removedChildProperty = false; for (CodegenProperty parentModelCodegenProperty : parentModelCodegenProperties) { - // Now that we have found a prop in the parent class, - // and search the child class for the same prop. - Iterator iterator = codegenProperties.iterator(); - while (iterator.hasNext()) { - CodegenProperty codegenProperty = iterator.next(); - if (codegenProperty.baseName == parentModelCodegenProperty.baseName) { - // We found a property in the child class that is - // a duplicate of the one in the parent, so remove it. - iterator.remove(); - removedChildProperty = true; - } - } - } - - if(removedChildProperty) { + // Now that we have found a prop in the parent class, + // and search the child class for the same prop. + Iterator iterator = codegenProperties.iterator(); + while (iterator.hasNext()) { + CodegenProperty codegenProperty = iterator.next(); + if (codegenProperty.baseName == parentModelCodegenProperty.baseName) { + // We found a property in the child class that is + // a duplicate of the one in the parent, so remove it. + iterator.remove(); + removedChildProperty = true; + } + } + } + + if (removedChildProperty) { // If we removed an entry from this model's vars, we need to ensure hasMore is updated int count = 0, numVars = codegenProperties.size(); - for(CodegenProperty codegenProperty : codegenProperties) { + for (CodegenProperty codegenProperty : codegenProperties) { count += 1; codegenProperty.hasMore = (count < numVars) ? true : false; } 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 cad2bf096323..3d0d35ce56df 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 @@ -4,24 +4,17 @@ import com.google.common.collect.Iterators; import com.google.common.collect.Lists; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.SupportingFile; - import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.models.parameters.HeaderParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.*; +import org.openapitools.codegen.mustache.*; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.core.util.Yaml; +import io.swagger.v3.parser.util.SchemaTypeUtil; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; @@ -80,17 +73,17 @@ public String getName() { @Override public String getHelp() { - return "Generates a swift client library."; + return "Generates a Swift 4.x client library."; } @Override protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, - ModelImpl swaggerModel) { + Schema schema) { - final Property additionalProperties = swaggerModel.getAdditionalProperties(); + final Schema additionalProperties = (Schema) schema.getAdditionalProperties(); if (additionalProperties != null) { - codegenModel.additionalPropertiesType = getSwaggerType(additionalProperties); + codegenModel.additionalPropertiesType = getSchemaType(additionalProperties); } } @@ -241,7 +234,7 @@ public Swift4Codegen() { "Flag to make all the API classes inner-class " + "of {{projectName}}API")); cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - "hides the timestamp when files were generated") + CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(LENIENT_TYPE_CAST, "Accept and cast values for simple types (string->bool, " @@ -253,17 +246,6 @@ public Swift4Codegen() { public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.TRUE.toString()); - } else { - Boolean hide = Boolean.valueOf(additionalProperties() - .get(CodegenConstants.HIDE_GENERATION_TIMESTAMP) - .toString()); - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, hide); - } - // Setup project name if (additionalProperties.containsKey(PROJECT_NAME)) { setProjectName((String) additionalProperties.get(PROJECT_NAME)); @@ -383,30 +365,29 @@ public String apiFileFolder() { } @Override - public String getTypeDeclaration(Property prop) { - if (prop instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) prop; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return "[" + getTypeDeclaration(inner) + "]"; - } else if (prop instanceof MapProperty) { - MapProperty mp = (MapProperty) prop; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return "[String:" + getTypeDeclaration(inner) + "]"; } - return super.getTypeDeclaration(prop); + return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property prop) { - String swaggerType = super.getSwaggerType(prop); + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); String type; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type) || defaultIncludes.contains(type)) { return type; } } else { - type = swaggerType; + type = openAPIType; } return toModelName(type); } @@ -478,20 +459,19 @@ public String toModelFilename(String name) { } @Override - public String toDefaultValue(Property prop) { + public String toDefaultValue(Schema prop) { // nil return null; } @Override - public String toInstantiationType(Property prop) { - if (prop instanceof MapProperty) { - MapProperty ap = (MapProperty) prop; - String inner = getSwaggerType(ap.getAdditionalProperties()); + public String toInstantiationType(Schema p) { + if (ModelUtils.isMapSchema(p)) { + String inner = getSchemaType((Schema) p.getAdditionalProperties()); return inner; - } else if (prop instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) prop; - String inner = getSwaggerType(ap.getItems()); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); return "[" + inner + "]"; } return null; @@ -574,7 +554,7 @@ public String toParamName(String name) { } @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + public CodegenModel fromModel(String name, Schema model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); if (codegenModel.description != null) { codegenModel.imports.add("ApiModel"); @@ -584,7 +564,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe // multilevel inheritance: reconcile properties of all the parents while (parentSchema != null) { - final Model parentModel = allDefinitions.get(parentSchema); + final Schema parentModel = allDefinitions.get(parentSchema); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftClientCodegen.java similarity index 91% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftClientCodegen.java index 18f4b42fc431..058acc13e3e1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftClientCodegen.java @@ -1,18 +1,20 @@ package org.openapitools.codegen.languages; import com.google.common.base.Predicate; - import com.google.common.collect.Iterators; import com.google.common.collect.Lists; + import org.openapitools.codegen.*; -import io.swagger.models.Swagger; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.parameters.HeaderParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.utils.*; +import org.openapitools.codegen.mustache.*; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.core.util.Yaml; +import io.swagger.v3.parser.util.SchemaTypeUtil; + import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.text.WordUtils; @@ -28,7 +30,7 @@ * 'swift3' or 'swift4' generator instead. */ -public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { +public class SwiftClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String PROJECT_NAME = "projectName"; public static final String RESPONSE_AS = "responseAs"; public static final String UNWRAP_REQUIRED = "unwrapRequired"; @@ -61,7 +63,7 @@ public CodegenType getTag() { @Override public String getName() { - return "swift"; + return "swift2-deprecated"; } @Override @@ -69,7 +71,7 @@ public String getHelp() { return "Generates a Swift (2.x) client library. IMPORTANT NOTE: this generator (swfit 2.x) is no longer actively maintained so please use 'swift3' or 'swift4' generator instead."; } - public SwiftCodegen() { + public SwiftClientCodegen() { super(); outputFolder = "generated-code" + File.separator + "swift"; modelTemplateFiles.put("model.mustache", ".swift"); @@ -78,6 +80,9 @@ public SwiftCodegen() { apiPackage = File.separator + "APIs"; modelPackage = File.separator + "Models"; + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + languageSpecificPrimitives = new HashSet( Arrays.asList( "Int", @@ -163,7 +168,7 @@ public SwiftCodegen() { cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec")); cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec")); cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class of {{projectName}}API")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); } @@ -171,13 +176,6 @@ public SwiftCodegen() { @Override public void processOpts() { super.processOpts(); - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } // Setup project name if (additionalProperties.containsKey(PROJECT_NAME)) { @@ -255,29 +253,28 @@ public String apiFileFolder() { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); return "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = (Schema) p.getAdditionalProperties(); return "[String:" + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); if (languageSpecificPrimitives.contains(type) || defaultIncludes.contains(type)) return type; } else - type = swaggerType; + type = schemaType; return toModelName(type); } @@ -343,27 +340,26 @@ public String toModelFilename(String name) { } @Override - public String toDefaultValue(Property p) { + public String toDefaultValue(Schema p) { // nil return null; } @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); + public String toInstantiationType(Schema p) { + if (ModelUtils.isMapSchema(p)) { + String inner = getSchemaType((Schema) p.getAdditionalProperties()); return "[String:" + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); return "[" + inner + "]"; } return null; } @Override - public CodegenProperty fromProperty(String name, Property p) { + public CodegenProperty fromProperty(String name, Schema p) { CodegenProperty codegenProperty = super.fromProperty(name, p); // TODO skip array/map of enum for the time being, // we need to add logic here to handle array/map of enum for any @@ -494,10 +490,10 @@ public String toParamName(String name) { } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, OpenAPI openAPI) { path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // issue 3914 - removed logic designed to remove any parameter of type HeaderParameter - return super.fromOperation(path, httpMethod, operation, definitions, swagger); + return super.fromOperation(path, httpMethod, operation, definitions, openAPI); } private static String normalizePath(String path) { 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 f9a390699586..50c255330bc8 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 @@ -10,14 +10,22 @@ import java.util.Map; import java.util.Set; +import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.CodegenParameter; import org.openapitools.codegen.CodegenOperation; import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.utils.ModelUtils; import org.openapitools.codegen.utils.SemVer; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.*; + +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.oas.models.info.*; public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen { private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm"); @@ -28,7 +36,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode public static final String NPM_REPOSITORY = "npmRepository"; public static final String SNAPSHOT = "snapshot"; public static final String WITH_INTERFACES = "withInterfaces"; - public static final String TAGGED_UNIONS ="taggedUnions"; + public static final String TAGGED_UNIONS = "taggedUnions"; public static final String NG_VERSION = "ngVersion"; protected String npmName = null; @@ -55,19 +63,19 @@ public TypeScriptAngularClientCodegen() { "Use this property to set an url your private npmRepo in the package.json")); this.cliOptions.add(new CliOption(SNAPSHOT, "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", - BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); + SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); this.cliOptions.add(new CliOption(WITH_INTERFACES, "Setting this property to true will generate interfaces next to the default class implementations.", - BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); + SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); this.cliOptions.add(new CliOption(TAGGED_UNIONS, - "Use discriminators to create tagged unions instead of extending interfaces.", - BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); + "Use discriminators to create tagged unions instead of extending interfaces.", + SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); this.cliOptions.add(new CliOption(NG_VERSION, "The version of Angular. Default is '4.3'")); } @Override - protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { - codegenModel.additionalPropertiesType = getTypeDeclaration(swaggerModel.getAdditionalProperties()); + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { + codegenModel.additionalPropertiesType = getTypeDeclaration((Schema) schema.getAdditionalProperties()); addImport(codegenModel, codegenModel.additionalPropertiesType); } @@ -166,11 +174,9 @@ public boolean isDataTypeFile(final String dataType) { } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof FileProperty) { + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isFileSchema(p)) { return "Blob"; - } else if (p instanceof ObjectProperty) { - return "any"; } else { return super.getTypeDeclaration(p); } @@ -178,13 +184,13 @@ public String getTypeDeclaration(Property p) { @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - if (isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { - return swaggerType; + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); + if (isLanguagePrimitive(openAPIType) || isLanguageGenericType(openAPIType)) { + return openAPIType; } - applyLocalTypeMapping(swaggerType); - return swaggerType; + applyLocalTypeMapping(openAPIType); + return openAPIType; } private String applyLocalTypeMapping(String type) { @@ -228,29 +234,29 @@ public Map postProcessOperations(Map operations) // Convert httpMethod to Angular's RequestMethod enum // https://angular.io/docs/ts/latest/api/http/index/RequestMethod-enum.html switch (op.httpMethod) { - case "GET": - op.httpMethod = "RequestMethod.Get"; - break; - case "POST": - op.httpMethod = "RequestMethod.Post"; - break; - case "PUT": - op.httpMethod = "RequestMethod.Put"; - break; - case "DELETE": - op.httpMethod = "RequestMethod.Delete"; - break; - case "OPTIONS": - op.httpMethod = "RequestMethod.Options"; - break; - case "HEAD": - op.httpMethod = "RequestMethod.Head"; - break; - case "PATCH": - op.httpMethod = "RequestMethod.Patch"; - break; - default: - throw new RuntimeException("Unknown HTTP Method " + op.httpMethod + " not allowed"); + case "GET": + op.httpMethod = "RequestMethod.Get"; + break; + case "POST": + op.httpMethod = "RequestMethod.Post"; + break; + case "PUT": + op.httpMethod = "RequestMethod.Put"; + break; + case "DELETE": + op.httpMethod = "RequestMethod.Delete"; + break; + case "OPTIONS": + op.httpMethod = "RequestMethod.Options"; + break; + case "HEAD": + op.httpMethod = "RequestMethod.Head"; + break; + case "PATCH": + op.httpMethod = "RequestMethod.Patch"; + break; + default: + throw new RuntimeException("Unknown HTTP Method " + op.httpMethod + " not allowed"); } } @@ -262,29 +268,29 @@ public Map postProcessOperations(Map operations) // Iterate through existing string, one character at a time. for (int i = 0; i < op.path.length(); i++) { switch (op.path.charAt(i)) { - case '{': - // We entered curly braces, so track that. - insideCurly++; - - // Add the more complicated component instead of just the brace. - pathBuffer.append("${encodeURIComponent(String("); - break; - case '}': - // We exited curly braces, so track that. - insideCurly--; - - // Add the more complicated component instead of just the brace. - pathBuffer.append(toVarName(parameterName.toString())); - pathBuffer.append("))}"); - parameterName.setLength(0); - break; - default: - if (insideCurly > 0) { - parameterName.append(op.path.charAt(i)); - } else { - pathBuffer.append(op.path.charAt(i)); - } - break; + case '{': + // We entered curly braces, so track that. + insideCurly++; + + // Add the more complicated component instead of just the brace. + pathBuffer.append("${encodeURIComponent(String("); + break; + case '}': + // We exited curly braces, so track that. + insideCurly--; + + // Add the more complicated component instead of just the brace. + pathBuffer.append(toVarName(parameterName.toString())); + pathBuffer.append("))}"); + parameterName.setLength(0); + break; + default: + if (insideCurly > 0) { + parameterName.append(op.path.charAt(i)); + } else { + pathBuffer.append(op.path.charAt(i)); + } + break; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularJsClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularJsClientCodegen.java index c3a22a9c485f..a2c464d12bcc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularJsClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularJsClientCodegen.java @@ -2,12 +2,34 @@ import java.io.File; -import org.openapitools.codegen.SupportingFile; +import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.CodegenParameter; -import io.swagger.models.properties.Property; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.utils.SemVer; + +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.oas.models.info.*; public class TypeScriptAngularJsClientCodegen extends AbstractTypeScriptClientCodegen { + public TypeScriptAngularJsClientCodegen() { + super(); + outputFolder = "generated-code/typescript-angularjs"; + modelTemplateFiles.put("model.mustache", ".ts"); + apiTemplateFiles.put("api.mustache", ".ts"); + embeddedTemplateDir = templateDir = "typescript-angularjs"; + apiPackage = "api"; + modelPackage = "model"; + } + @Override public String getName() { return "typescript-angularjs"; @@ -29,24 +51,14 @@ public void processOpts() { supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); } - - public TypeScriptAngularJsClientCodegen() { - super(); - outputFolder = "generated-code/typescript-angularjs"; - modelTemplateFiles.put("model.mustache", ".ts"); - apiTemplateFiles.put("api.mustache", ".ts"); - embeddedTemplateDir = templateDir = "typescript-angularjs"; - apiPackage = "api"; - modelPackage = "model"; - } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - if(isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { - return swaggerType; + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); + if (isLanguagePrimitive(openAPIType) || isLanguageGenericType(openAPIType)) { + return openAPIType; } - return addModelPrefix(swaggerType); + return addModelPrefix(openAPIType); } @Override @@ -60,16 +72,16 @@ private String getIndexDirectory() { return indexPackage.replace('.', File.separatorChar); } - private String addModelPrefix(String swaggerType) { + private String addModelPrefix(String openAPIType) { String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); } else { - type = swaggerType; + type = openAPIType; } if (!isLanguagePrimitive(type) && !isLanguageGenericType(type)) { - type = "models." + swaggerType; + type = "models." + openAPIType; } return type; } @@ -79,8 +91,8 @@ private boolean isLanguagePrimitive(String type) { } private boolean isLanguageGenericType(String type) { - for (String genericType: languageGenericTypes) { - if (type.startsWith(genericType + "<")) { + for (String genericType : languageGenericTypes) { + if (type.startsWith(genericType + "<")) { return true; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAureliaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAureliaClientCodegen.java index 3efc1eef52c1..c71af8bc98f1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAureliaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAureliaClientCodegen.java @@ -1,7 +1,16 @@ package org.openapitools.codegen.languages; +import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.oas.models.info.*; + import java.util.HashSet; import java.util.List; import java.util.Map; @@ -30,31 +39,6 @@ public TypeScriptAureliaClientCodegen() { this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package")); } - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(NPM_NAME)) { - this.setNpmName(additionalProperties.get(NPM_NAME).toString()); - } - - if (additionalProperties.containsKey(NPM_VERSION)) { - this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString()); - } - - // Set supporting files - supportingFiles.add(new SupportingFile("models.mustache", "", "models.ts")); - supportingFiles.add(new SupportingFile("index.ts.mustache", "", "index.ts")); - supportingFiles.add(new SupportingFile("Api.ts.mustache", "", "Api.ts")); - supportingFiles.add(new SupportingFile("AuthStorage.ts.mustache", "", "AuthStorage.ts")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("README.md", "", "README.md")); - supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json")); - supportingFiles.add(new SupportingFile("tsconfig.json.mustache", "", "tsconfig.json")); - supportingFiles.add(new SupportingFile("tslint.json.mustache", "", "tslint.json")); - supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); - } - @Override public String getName() { return "typescript-aurelia"; @@ -81,6 +65,31 @@ public void setNpmVersion(String npmVersion) { this.npmVersion = npmVersion; } + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(NPM_NAME)) { + this.setNpmName(additionalProperties.get(NPM_NAME).toString()); + } + + if (additionalProperties.containsKey(NPM_VERSION)) { + this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString()); + } + + // Set supporting files + supportingFiles.add(new SupportingFile("models.mustache", "", "models.ts")); + supportingFiles.add(new SupportingFile("index.ts.mustache", "", "index.ts")); + supportingFiles.add(new SupportingFile("Api.ts.mustache", "", "Api.ts")); + supportingFiles.add(new SupportingFile("AuthStorage.ts.mustache", "", "AuthStorage.ts")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json")); + supportingFiles.add(new SupportingFile("tsconfig.json.mustache", "", "tsconfig.json")); + supportingFiles.add(new SupportingFile("tslint.json.mustache", "", "tslint.json")); + supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); + } + @Override public Map postProcessOperations(Map objs) { objs = super.postProcessOperations(objs); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java index 0fa1643b510f..5be02d957413 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java @@ -1,11 +1,16 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.SupportingFile; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.*; +import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.oas.models.info.*; import java.io.File; import java.text.SimpleDateFormat; @@ -18,6 +23,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege public static final String NPM_VERSION = "npmVersion"; public static final String NPM_REPOSITORY = "npmRepository"; public static final String SNAPSHOT = "snapshot"; + public static final String WITH_INTERFACES = "withInterfaces"; protected String npmName = null; protected String npmVersion = "1.0.0"; @@ -36,13 +42,42 @@ public TypeScriptFetchClientCodegen() { this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package")); this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package")); this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json")); - this.cliOptions.add(new CliOption(SNAPSHOT, "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(SNAPSHOT, "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(WITH_INTERFACES, "Setting this property to true will generate interfaces next to the default class implementations.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); } @Override - protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { - codegenModel.additionalPropertiesType = getTypeDeclaration(swaggerModel.getAdditionalProperties()); - addImport(codegenModel, codegenModel.additionalPropertiesType); + public String getName() { + return "typescript-fetch"; + } + + @Override + public String getHelp() { + return "Generates a TypeScript client library using Fetch API (beta)."; + } + + public String getNpmName() { + return npmName; + } + + public void setNpmName(String npmName) { + this.npmName = npmName; + } + + public String getNpmVersion() { + return npmVersion; + } + + public void setNpmVersion(String npmVersion) { + this.npmVersion = npmVersion; + } + + public String getNpmRepository() { + return npmRepository; + } + + public void setNpmRepository(String npmRepository) { + this.npmRepository = npmRepository; } @Override @@ -61,23 +96,29 @@ public void processOpts() { } @Override - public String getTypeDeclaration(Property p) { - Property inner; - if(p instanceof ArrayProperty) { - ArrayProperty mp1 = (ArrayProperty)p; - inner = mp1.getItems(); - return this.getSwaggerType(p) + "<" + this.getTypeDeclaration(inner) + ">"; - } else if(p instanceof MapProperty) { - MapProperty mp = (MapProperty)p; - inner = mp.getAdditionalProperties(); + public String getTypeDeclaration(Schema p) { + Schema inner; + if (ModelUtils.isArraySchema(p)) { + inner = ((ArraySchema) p).getItems(); + return this.getSchemaType(p) + "<" + this.getTypeDeclaration(inner) + ">"; + } else if (ModelUtils.isMapSchema(p)) { + inner = (Schema) p.getAdditionalProperties(); return "{ [key: string]: " + this.getTypeDeclaration(inner) + "; }"; - } else if(p instanceof FileProperty || p instanceof ObjectProperty) { + } else if (ModelUtils.isFileSchema(p)) { + return "any"; + } else if (ModelUtils.isBinarySchema(p)) { return "any"; } else { return super.getTypeDeclaration(p); } } + @Override + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { + codegenModel.additionalPropertiesType = getTypeDeclaration((Schema) schema.getAdditionalProperties()); + addImport(codegenModel, codegenModel.additionalPropertiesType); + } + private void addNpmPackageGeneration() { if (additionalProperties.containsKey(NPM_NAME)) { this.setNpmName(additionalProperties.get(NPM_NAME).toString()); @@ -102,38 +143,4 @@ private void addNpmPackageGeneration() { supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json")); } - @Override - public String getName() { - return "typescript-fetch"; - } - - @Override - public String getHelp() { - return "Generates a TypeScript client library using Fetch API (beta)."; - } - - public String getNpmName() { - return npmName; - } - - public void setNpmName(String npmName) { - this.npmName = npmName; - } - - public String getNpmVersion() { - return npmVersion; - } - - public void setNpmVersion(String npmVersion) { - this.npmVersion = npmVersion; - } - - public String getNpmRepository() { - return npmRepository; - } - - public void setNpmRepository(String npmRepository) { - this.npmRepository = npmRepository; - } - } 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 new file mode 100644 index 000000000000..eab76efc8e3f --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java @@ -0,0 +1,372 @@ +package org.openapitools.codegen.languages; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.languages.features.BeanValidationFeatures; +import org.openapitools.codegen.languages.features.JbossFeature; +import org.openapitools.codegen.languages.features.SwaggerFeatures; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.media.*; + + +public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCodegen { + private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm"); + private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value"; + + public static final String NPM_NAME = "npmName"; + public static final String NPM_VERSION = "npmVersion"; + public static final String NPM_REPOSITORY = "npmRepository"; + public static final String SNAPSHOT = "snapshot"; + public static final String WITH_INTERFACES = "withInterfaces"; + public static final String USE_PROMISE = "usePromise"; + public static final String TAGGED_UNIONS = "taggedUnions"; + + protected String npmVersion = null; + protected String npmName = null; + protected String npmRepository = null; + private boolean taggedUnions = false; + + public TypeScriptInversifyClientCodegen() { + super(); + this.outputFolder = "generated-code/typescript-inversify"; + + embeddedTemplateDir = templateDir = "typescript-inversify"; + modelTemplateFiles.put("model.mustache", ".ts"); + apiTemplateFiles.put("api.service.mustache", ".ts"); + languageSpecificPrimitives.add("Blob"); + typeMapping.put("file", "Blob"); + apiPackage = "api"; + modelPackage = "model"; + + this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package")); + this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package")); + this.cliOptions.add(new CliOption(NPM_REPOSITORY, + "Use this property to set an url your private npmRepo in the package.json")); + this.cliOptions.add(new CliOption(SNAPSHOT, + "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", + SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(WITH_INTERFACES, + "Setting this property to true will generate interfaces next to the default class implementations.", + SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(USE_PROMISE, + "Setting this property to use promise instead of observable inside every service.", + SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(TAGGED_UNIONS, + "Use discriminators to create tagged unions instead of extending interfaces.", + SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); + } + + @Override + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { + codegenModel.additionalPropertiesType = getTypeDeclaration((Schema) schema.getAdditionalProperties()); + addImport(codegenModel, codegenModel.additionalPropertiesType); + } + + @Override + public String getName() { + return "typescript-inversify"; + } + + @Override + public String getHelp() { + return "Generates Typescript services using Inversify IOC"; + } + + @Override + public void processOpts() { + super.processOpts(); + // HttpClient + supportingFiles.add(new SupportingFile("IHttpClient.mustache", getIndexDirectory(), "IHttpClient.ts")); + supportingFiles.add(new SupportingFile("IAPIConfiguration.mustache", getIndexDirectory(), "IAPIConfiguration.ts")); + supportingFiles.add(new SupportingFile("HttpClient.mustache", getIndexDirectory(), "HttpClient.ts")); + supportingFiles.add(new SupportingFile("HttpResponse.mustache", getIndexDirectory(), "HttpResponse.ts")); + supportingFiles.add(new SupportingFile("Headers.mustache", getIndexDirectory(), "Headers.ts")); + + supportingFiles.add(new SupportingFile("ApiServiceBinder.mustache", getIndexDirectory(), "ApiServiceBinder.ts")); + supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts")); + + if (additionalProperties.containsKey(NPM_NAME)) { + addNpmPackageGeneration(); + } + + if (additionalProperties.containsKey(WITH_INTERFACES)) { + boolean withInterfaces = Boolean.parseBoolean(additionalProperties.get(WITH_INTERFACES).toString()); + if (withInterfaces) { + apiTemplateFiles.put("apiInterface.mustache", "Interface.ts"); + } + } + + if (additionalProperties.containsKey(TAGGED_UNIONS)) { + taggedUnions = Boolean.parseBoolean(additionalProperties.get(TAGGED_UNIONS).toString()); + } + } + + private void addNpmPackageGeneration() { + if (additionalProperties.containsKey(NPM_NAME)) { + this.setNpmName(additionalProperties.get(NPM_NAME).toString()); + } + + if (additionalProperties.containsKey(NPM_VERSION)) { + this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString()); + } + + if (additionalProperties.containsKey(SNAPSHOT) + && Boolean.valueOf(additionalProperties.get(SNAPSHOT).toString())) { + this.setNpmVersion(npmVersion + "-SNAPSHOT." + SNAPSHOT_SUFFIX_FORMAT.format(new Date())); + } + additionalProperties.put(NPM_VERSION, npmVersion); + + if (additionalProperties.containsKey(NPM_REPOSITORY)) { + this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString()); + } + + //Files for building our lib + supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts")); + supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts")); + supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts")); + supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("README.mustache", getIndexDirectory(), "README.md")); + supportingFiles.add(new SupportingFile("package.mustache", getIndexDirectory(), "package.json")); + supportingFiles.add(new SupportingFile("tsconfig.mustache", getIndexDirectory(), "tsconfig.json")); + } + + private String getIndexDirectory() { + String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.'))); + return indexPackage.replace('.', File.separatorChar); + } + + @Override + public boolean isDataTypeFile(final String dataType) { + return dataType != null && dataType.equals("Blob"); + } + + @Override + public String getTypeDeclaration(Schema p) { + if (p instanceof FileSchema) { + return "Blob"; + } else { + return super.getTypeDeclaration(p); + } + } + + + @Override + public String getSchemaType(Schema p) { + String swaggerType = super.getSchemaType(p); + if (isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { + return swaggerType; + } + applyLocalTypeMapping(swaggerType); + return swaggerType; + } + + private String applyLocalTypeMapping(String type) { + if (typeMapping.containsKey(type)) { + type = typeMapping.get(type); + } + return type; + } + + private boolean isLanguagePrimitive(String type) { + return languageSpecificPrimitives.contains(type); + } + + private boolean isLanguageGenericType(String type) { + for (String genericType : languageGenericTypes) { + if (type.startsWith(genericType + "<")) { + return true; + } + } + return false; + } + + @Override + public void postProcessParameter(CodegenParameter parameter) { + super.postProcessParameter(parameter); + parameter.dataType = applyLocalTypeMapping(parameter.dataType); + } + + @Override + public Map postProcessOperations(Map operations) { + Map objs = (Map) operations.get("operations"); + + // Add filename information for api imports + objs.put("apiFilename", getApiFilenameFromClassname(objs.get("classname").toString())); + + List ops = (List) objs.get("operation"); + for (CodegenOperation op : ops) { + // Prep a string buffer where we're going to set up our new version of the string. + StringBuilder pathBuffer = new StringBuilder(); + StringBuilder parameterName = new StringBuilder(); + int insideCurly = 0; + + op.httpMethod = op.httpMethod.toLowerCase(); + + // Iterate through existing string, one character at a time. + for (int i = 0; i < op.path.length(); i++) { + switch (op.path.charAt(i)) { + case '{': + // We entered curly braces, so track that. + insideCurly++; + + // Add the more complicated component instead of just the brace. + pathBuffer.append("${encodeURIComponent(String("); + break; + case '}': + // We exited curly braces, so track that. + insideCurly--; + + // Add the more complicated component instead of just the brace. + pathBuffer.append(toVarName(parameterName.toString())); + pathBuffer.append("))}"); + parameterName.setLength(0); + break; + default: + if (insideCurly > 0) { + parameterName.append(op.path.charAt(i)); + } else { + pathBuffer.append(op.path.charAt(i)); + } + break; + } + } + + // Overwrite path to TypeScript template string, after applying everything we just did. + op.path = pathBuffer.toString(); + } + + // Add additional filename information for model imports in the services + List> imports = (List>) operations.get("imports"); + for (Map im : imports) { + im.put("filename", im.get("import")); + im.put("classname", getModelnameFromModelFilename(im.get("filename").toString())); + } + + return operations; + } + + @Override + public Map postProcessModels(Map objs) { + Map result = super.postProcessModels(objs); + + return postProcessModelsEnum(result); + } + + @Override + public Map postProcessAllModels(Map objs) { + Map result = super.postProcessAllModels(objs); + + for (Map.Entry entry : result.entrySet()) { + Map inner = (Map) entry.getValue(); + List> models = (List>) inner.get("models"); + for (Map mo : models) { + CodegenModel cm = (CodegenModel) mo.get("model"); + if (taggedUnions) { + mo.put(TAGGED_UNIONS, true); + if (cm.discriminator != null && cm.children != null) { + for (CodegenModel child : cm.children) { + cm.imports.add(child.classname); + } + } + if (cm.parent != null) { + cm.imports.remove(cm.parent); + } + } + // Add additional filename information for imports + mo.put("tsImports", toTsImports(cm, cm.imports)); + } + } + return result; + } + + private List> toTsImports(CodegenModel cm, Set imports) { + List> tsImports = new ArrayList<>(); + for (String im : imports) { + if (!im.equals(cm.classname)) { + HashMap tsImport = new HashMap<>(); + tsImport.put("classname", im); + tsImport.put("filename", toModelFilename(im)); + tsImports.add(tsImport); + } + } + return tsImports; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultService"; + } + return initialCaps(name) + "Service"; + } + + @Override + public String toApiFilename(String name) { + if (name.length() == 0) { + return "default.service"; + } + return camelize(name, true) + ".service"; + } + + @Override + public String toApiImport(String name) { + return apiPackage() + "/" + toApiFilename(name); + } + + @Override + public String toModelFilename(String name) { + return camelize(toModelName(name), true); + } + + @Override + public String toModelImport(String name) { + return modelPackage() + "/" + toModelFilename(name); + } + + public String getNpmName() { + return npmName; + } + + public void setNpmName(String npmName) { + this.npmName = npmName; + } + + public String getNpmVersion() { + return npmVersion; + } + + public void setNpmVersion(String npmVersion) { + this.npmVersion = npmVersion; + } + + public String getNpmRepository() { + return npmRepository; + } + + public void setNpmRepository(String npmRepository) { + this.npmRepository = npmRepository; + } + + private String getApiFilenameFromClassname(String classname) { + String name = classname.substring(0, classname.length() - "Service".length()); + return toApiFilename(name); + } + + private String getModelnameFromModelFilename(String filename) { + String name = filename.substring((modelPackage() + "/").length()); + return camelize(name); + } + +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java index 00079b9b032a..d449aae45f6f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java @@ -1,19 +1,23 @@ package org.openapitools.codegen.languages; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenParameter; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.*; +import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.*; +import io.swagger.v3.oas.models.parameters.*; +import io.swagger.v3.oas.models.info.*; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.SupportingFile; - public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptJqueryClientCodegen.class); private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm"); @@ -43,8 +47,42 @@ public TypeScriptJqueryClientCodegen() { this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package")); this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package")); this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json")); - this.cliOptions.add(new CliOption(SNAPSHOT, "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); - this.cliOptions.add(new CliOption(JQUERY_ALREADY_IMPORTED, "When using this in legacy app using mix of typescript and javascript, this will only declare jquery and not import it", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(SNAPSHOT, + "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", + SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(JQUERY_ALREADY_IMPORTED, + "When using this in legacy app using mix of typescript and javascript, this will only declare jquery and not import it", + SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); + } + + @Override + public String getName() { + return "typescript-jquery"; + } + + @Override + public String getHelp() { + return "Generates a TypeScript jquery client library."; + } + + public void setNpmName(String npmName) { + this.npmName = npmName; + } + + public void setNpmVersion(String npmVersion) { + this.npmVersion = npmVersion; + } + + public String getNpmVersion() { + return npmVersion; + } + + public String getNpmRepository() { + return npmRepository; + } + + public void setNpmRepository(String npmRepository) { + this.npmRepository = npmRepository; } @Override @@ -58,42 +96,51 @@ public void processOpts() { supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts")); supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts")); - LOGGER.warn("check additionals: " + additionalProperties.get(NPM_NAME)); + //LOGGER.warn("check additionals: " + additionalProperties.get(NPM_NAME)); if (additionalProperties.containsKey(NPM_NAME)) { addNpmPackageGeneration(); } } - private String getIndexDirectory() { - String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.'))); - return indexPackage.replace('.', File.separatorChar); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - if (p instanceof StringProperty) { - StringProperty sp = (StringProperty) p; - if (sp.getEnum() != null) { - return swaggerType; + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); + if (ModelUtils.isStringSchema(p)) { + if (p.getEnum() != null) { + return openAPIType; } } - if (isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { - return swaggerType; + if (isLanguagePrimitive(openAPIType) || isLanguageGenericType(openAPIType)) { + return openAPIType; + } + return addModelPrefix(openAPIType); + } + + @Override + public void postProcessParameter(CodegenParameter parameter) { + super.postProcessParameter(parameter); + + if (!parameter.isEnum) { + parameter.dataType = addModelPrefix(parameter.dataType); } - return addModelPrefix(swaggerType); } - private String addModelPrefix(String swaggerType) { + @Override + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { + codegenModel.additionalPropertiesType = getSchemaType((Schema) schema.getAdditionalProperties()); + addImport(codegenModel, codegenModel.additionalPropertiesType); + } + + private String addModelPrefix(String openAPIType) { String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); } else { - type = swaggerType; + type = openAPIType; } if (!isLanguagePrimitive(type) && !isLanguageGenericType(type)) { - type = "models." + swaggerType; + type = "models." + openAPIType; } return type; } @@ -111,13 +158,9 @@ private boolean isLanguageGenericType(String type) { return false; } - @Override - public void postProcessParameter(CodegenParameter parameter) { - super.postProcessParameter(parameter); - - if (!parameter.isEnum) { - parameter.dataType = addModelPrefix(parameter.dataType); - } + private String getPackageRootDirectory() { + String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.'))); + return indexPackage.replace('.', File.separatorChar); } private void addNpmPackageGeneration() { @@ -145,45 +188,9 @@ private void addNpmPackageGeneration() { supportingFiles.add(new SupportingFile("tsconfig.mustache", getPackageRootDirectory(), "tsconfig.json")); } - private String getPackageRootDirectory() { + private String getIndexDirectory() { String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.'))); return indexPackage.replace('.', File.separatorChar); } - @Override - protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { - codegenModel.additionalPropertiesType = getSwaggerType(swaggerModel.getAdditionalProperties()); - addImport(codegenModel, codegenModel.additionalPropertiesType); - } - - @Override - public String getName() { - return "typescript-jquery"; - } - - @Override - public String getHelp() { - return "Generates a TypeScript jquery client library."; - } - - - public void setNpmName(String npmName) { - this.npmName = npmName; - } - - public void setNpmVersion(String npmVersion) { - this.npmVersion = npmVersion; - } - - public String getNpmVersion() { - return npmVersion; - } - - public String getNpmRepository() { - return npmRepository; - } - - public void setNpmRepository(String npmRepository) { - this.npmRepository = npmRepository; - } } 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 24361995df84..ec2667239b84 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 @@ -1,7 +1,6 @@ package org.openapitools.codegen.languages; -import io.swagger.models.properties.FileProperty; -import io.swagger.models.properties.Property; +import io.swagger.v3.parser.util.SchemaTypeUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -9,9 +8,10 @@ import java.text.SimpleDateFormat; import java.util.Date; -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.BooleanProperty; +import org.openapitools.codegen.*; +import org.openapitools.codegen.utils.ModelUtils; + +import io.swagger.v3.oas.models.media.*; public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNodeClientCodegen.class); @@ -41,48 +41,9 @@ public TypeScriptNodeClientCodegen() { this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package")); this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package")); this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json")); - this.cliOptions.add(new CliOption(SNAPSHOT, "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); - } - - - @Override - public void processOpts() { - super.processOpts(); - supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); - - if(additionalProperties.containsKey(NPM_NAME)) { - addNpmPackageGeneration(); - } - } - - private void addNpmPackageGeneration() { - if(additionalProperties.containsKey(NPM_NAME)) { - this.setNpmName(additionalProperties.get(NPM_NAME).toString()); - } - - if (additionalProperties.containsKey(NPM_VERSION)) { - this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString()); - } - - if (additionalProperties.containsKey(SNAPSHOT) && Boolean.valueOf(additionalProperties.get(SNAPSHOT).toString())) { - this.setNpmVersion(npmVersion + "-SNAPSHOT." + SNAPSHOT_SUFFIX_FORMAT.format(new Date())); - } - additionalProperties.put(NPM_VERSION, npmVersion); - - if (additionalProperties.containsKey(NPM_REPOSITORY)) { - this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString()); - } - - //Files for building our lib - supportingFiles.add(new SupportingFile("package.mustache", getPackageRootDirectory(), "package.json")); - supportingFiles.add(new SupportingFile("tsconfig.mustache", getPackageRootDirectory(), "tsconfig.json")); - } - - private String getPackageRootDirectory() { - String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.'))); - return indexPackage.replace('.', File.separatorChar); + this.cliOptions.add(new CliOption(SNAPSHOT, + "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", + SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); } @Override @@ -92,23 +53,24 @@ public String getName() { @Override public String getHelp() { - return "Generates a TypeScript nodejs client library."; + return "Generates a TypeScript NodeJS client library."; } @Override public boolean isDataTypeFile(final String dataType) { - return dataType != null && dataType.equals("Buffer"); + return "Buffer".equals(dataType); } @Override - public String getTypeDeclaration(Property p) { - if (p instanceof FileProperty) { + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isFileSchema(p)) { + return "Buffer"; + } else if (ModelUtils.isBinarySchema(p)) { return "Buffer"; } return super.getTypeDeclaration(p); } - public void setNpmName(String npmName) { this.npmName = npmName; } @@ -128,4 +90,44 @@ public String getNpmRepository() { public void setNpmRepository(String npmRepository) { this.npmRepository = npmRepository; } + + @Override + public void processOpts() { + super.processOpts(); + supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); + + if (additionalProperties.containsKey(NPM_NAME)) { + addNpmPackageGeneration(); + } + } + + private void addNpmPackageGeneration() { + if (additionalProperties.containsKey(NPM_NAME)) { + this.setNpmName(additionalProperties.get(NPM_NAME).toString()); + } + + if (additionalProperties.containsKey(NPM_VERSION)) { + this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString()); + } + + if (additionalProperties.containsKey(SNAPSHOT) && Boolean.valueOf(additionalProperties.get(SNAPSHOT).toString())) { + this.setNpmVersion(npmVersion + "-SNAPSHOT." + SNAPSHOT_SUFFIX_FORMAT.format(new Date())); + } + additionalProperties.put(NPM_VERSION, npmVersion); + + if (additionalProperties.containsKey(NPM_REPOSITORY)) { + this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString()); + } + + //Files for building our lib + supportingFiles.add(new SupportingFile("package.mustache", getPackageRootDirectory(), "package.json")); + supportingFiles.add(new SupportingFile("tsconfig.mustache", getPackageRootDirectory(), "tsconfig.json")); + } + + private String getPackageRootDirectory() { + String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.'))); + return indexPackage.replace('.', File.separatorChar); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/BeanValidationExtendedFeatures.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/BeanValidationExtendedFeatures.java index 9b2b11305f0d..aeb731b70cff 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/BeanValidationExtendedFeatures.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/BeanValidationExtendedFeatures.java @@ -4,8 +4,8 @@ public interface BeanValidationExtendedFeatures { // Language (implementing Client/Server) supports automatic BeanValidation (1.1) public static final String USE_BEANVALIDATION_FEATURE = "useBeanValidationFeature"; - + public void setUseBeanValidationFeature(boolean useBeanValidationFeature); - + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/BeanValidationFeatures.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/BeanValidationFeatures.java index d5a16cf465fa..0e3bdc004206 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/BeanValidationFeatures.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/BeanValidationFeatures.java @@ -6,5 +6,5 @@ public interface BeanValidationFeatures { public static final String USE_BEANVALIDATION = "useBeanValidation"; public void setUseBeanValidation(boolean useBeanValidation); - + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFFeatures.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFFeatures.java index 4a36cefc155e..00ec1eb62c65 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFFeatures.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFFeatures.java @@ -2,10 +2,8 @@ /** * Features supported by CXF 3 (client + server) - * */ public interface CXFFeatures extends LoggingFeatures, GzipFeatures, BeanValidationFeatures { - } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFServerFeatures.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFServerFeatures.java index 83233750fa25..799b10d6b5e6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFServerFeatures.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFServerFeatures.java @@ -2,16 +2,14 @@ /** * Features supported by CXF 3 server - * */ public interface CXFServerFeatures - extends CXFFeatures, SwaggerFeatures, SpringFeatures, JbossFeature, BeanValidationExtendedFeatures, SwaggerUIFeatures -{ - + extends CXFFeatures, SwaggerFeatures, SpringFeatures, JbossFeature, BeanValidationExtendedFeatures, SwaggerUIFeatures { + public static final String USE_WADL_FEATURE = "useWadlFeature"; - + public static final String USE_MULTIPART_FEATURE = "useMultipartFeature"; - + public static final String ADD_CONSUMES_PRODUCES_JSON = "addConsumesProducesJson"; public static final String USE_ANNOTATED_BASE_PATH = "useAnnotatedBasePath"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/GzipFeatures.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/GzipFeatures.java index b096f143f2ac..9c919ea16122 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/GzipFeatures.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/GzipFeatures.java @@ -1,7 +1,7 @@ package org.openapitools.codegen.languages.features; public interface GzipFeatures { - + public static final String USE_GZIP_FEATURE = "useGzipFeature"; public void setUseGzipFeature(boolean useGzipFeature); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/PerformBeanValidationFeatures.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/PerformBeanValidationFeatures.java index de846f84fc5a..74b6886ec06b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/PerformBeanValidationFeatures.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/PerformBeanValidationFeatures.java @@ -6,5 +6,5 @@ public interface PerformBeanValidationFeatures { public static final String PERFORM_BEANVALIDATION = "performBeanValidation"; public void setPerformBeanValidation(boolean performBeanValidation); - + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/SpringFeatures.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/SpringFeatures.java index b52643a0ef9c..691fdd40eef8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/SpringFeatures.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/SpringFeatures.java @@ -3,13 +3,13 @@ public interface SpringFeatures extends BeanValidationFeatures { public static final String GENERATE_SPRING_APPLICATION = "generateSpringApplication"; - + public static final String GENERATE_SPRING_BOOT_APPLICATION = "generateSpringBootApplication"; public static final String USE_SPRING_ANNOTATION_CONFIG = "useSpringAnnotationConfig"; public void setGenerateSpringApplication(boolean useGenerateSpringApplication); - + public void setGenerateSpringBootApplication(boolean generateSpringBootApplication); public void setUseSpringAnnotationConfig(boolean useSpringAnnotationConfig); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java index d114a03e880e..c1586600fd2c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java @@ -1,15 +1,30 @@ package org.openapitools.codegen.utils; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.parameters.RequestBody; +import io.swagger.v3.parser.util.SchemaTypeUtil; import org.openapitools.codegen.CodegenModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.commons.lang3.StringUtils; + + public class ModelUtils { + static Logger LOGGER = LoggerFactory.getLogger(ModelUtils.class); + /** * Searches for the model by name in the map of models and returns it * - * @param name Name of the model + * @param name Name of the model * @param models Map of models * @return model */ @@ -33,4 +48,277 @@ public static CodegenModel getModelByName(final String name, final Map getUnusedSchemas(OpenAPI openAPI) { + List unusedSchemas = new ArrayList(); + + // no model defined + if (openAPI.getComponents().getSchemas() == null) { + openAPI.getComponents().setSchemas(new HashMap()); + } + + // operations + Map paths = openAPI.getPaths(); + Map schemas = openAPI.getComponents().getSchemas(); + + if (paths != null) { + for (String pathname : paths.keySet()) { + PathItem path = paths.get(pathname); + Map operationMap = path.readOperationsMap(); + if (operationMap != null) { + for (PathItem.HttpMethod method : operationMap.keySet()) { + Operation operation = operationMap.get(method); + RequestBody requestBody = operation.getRequestBody(); + + if (requestBody == null) { + continue; + } + + //LOGGER.info("debugging resolver: " + requestBody.toString()); + if (requestBody.getContent() == null) { + continue; + } + + // go through "content" + for (String mimeType : requestBody.getContent().keySet()) { + if ("application/x-www-form-urlencoded".equalsIgnoreCase(mimeType) || + "multipart/form-data".equalsIgnoreCase(mimeType)) { + // remove the schema that's automatically created by the parser + MediaType mediaType = requestBody.getContent().get(mimeType); + if (mediaType.getSchema().get$ref() != null) { + LOGGER.debug("mark schema (form parameters) as unused: " + getSimpleRef(mediaType.getSchema().get$ref())); + unusedSchemas.add(getSimpleRef(mediaType.getSchema().get$ref())); + } + } + } + } + } + } + } + + return unusedSchemas; + } + + // todo change it to public later + public static String getSimpleRef(String ref) { + if (ref.startsWith("#/components/")) { + ref = ref.substring(ref.lastIndexOf("/") + 1); + } else if (ref.startsWith("#/definitions/")) { + ref = ref.substring(ref.lastIndexOf("/") + 1); + } + + return ref; + } + + public static boolean isObjectSchema(Schema schema) { + if (schema instanceof ObjectSchema) { + return true; + } + if (SchemaTypeUtil.OBJECT_TYPE.equals(schema.getType()) && !(schema instanceof MapSchema)) { + return true; + } + if (schema.getType() == null && schema.getProperties() != null && !schema.getProperties().isEmpty()) { + return true; + } + return false; + } + + public static boolean isComposedSchema(Schema schema) { + if (schema instanceof ComposedSchema) { + return true; + } + return false; + } + + public static boolean isMapSchema(Schema schema) { + if (schema instanceof MapSchema) { + return true; + } + if (schema.getAdditionalProperties() != null) { + return true; + } + return false; + } + + public static boolean isArraySchema(Schema schema) { + if (schema instanceof ArraySchema) { + return true; + } + // assume it's an array if maxItems, minItems is set + if (schema.getMaxItems() != null || schema.getMinItems() != null) { + return true; + } + return false; + } + + public static boolean isStringSchema(Schema schema) { + if (schema instanceof StringSchema || SchemaTypeUtil.STRING_TYPE.equals(schema.getType())) { + return true; + } + return false; + } + + public static boolean isIntegerSchema(Schema schema) { + if (schema instanceof IntegerSchema) { + return true; + } + if (SchemaTypeUtil.INTEGER_TYPE.equals(schema.getType())) { + return true; + } + return false; + } + + public static boolean isShortchema(Schema schema) { + if (SchemaTypeUtil.INTEGER_TYPE.equals(schema.getType()) // type: integer + && SchemaTypeUtil.INTEGER32_FORMAT.equals(schema.getFormat())) { // format: short (int32) + return true; + } + return false; + } + + public static boolean isLongSchema(Schema schema) { + if (SchemaTypeUtil.INTEGER_TYPE.equals(schema.getType()) // type: integer + && SchemaTypeUtil.INTEGER64_FORMAT.equals(schema.getFormat())) { // format: long (int64) + return true; + } + return false; + } + + public static boolean isBooleanSchema(Schema schema) { + if (schema instanceof BooleanSchema) { + return true; + } + if (SchemaTypeUtil.BOOLEAN_TYPE.equals(schema.getType())) { + return true; + } + return false; + } + + public static boolean isNumberSchema(Schema schema) { + if (schema instanceof NumberSchema) { + return true; + } + if (SchemaTypeUtil.NUMBER_TYPE.equals(schema.getType())) { + return true; + } + return false; + } + + public static boolean isFloatSchema(Schema schema) { + if (SchemaTypeUtil.NUMBER_TYPE.equals(schema.getType()) + && SchemaTypeUtil.FLOAT_FORMAT.equals(schema.getFormat())) { // format: float + return true; + } + return false; + } + + public static boolean isDoubleSchema(Schema schema) { + if (schema instanceof NumberSchema) { + return true; + } + if (SchemaTypeUtil.NUMBER_TYPE.equals(schema.getType()) + && SchemaTypeUtil.DOUBLE_FORMAT.equals(schema.getFormat())) { // format: double + return true; + } + return false; + } + + public static boolean isDateSchema(Schema schema) { + if (schema instanceof DateSchema) { + return true; + } + + if (SchemaTypeUtil.STRING_TYPE.equals(schema.getType()) + && SchemaTypeUtil.DATE_FORMAT.equals(schema.getFormat())) { // format: date + return true; + } + return false; + } + + public static boolean isDateTimeSchema(Schema schema) { + if (schema instanceof DateTimeSchema) { + return true; + } + if (SchemaTypeUtil.STRING_TYPE.equals(schema.getType()) + && SchemaTypeUtil.DATE_TIME_FORMAT.equals(schema.getFormat())) { // format: date-time + return true; + } + return false; + } + + public static boolean isPasswordSchema(Schema schema) { + if (schema instanceof PasswordSchema) { + return true; + } + if (SchemaTypeUtil.STRING_TYPE.equals(schema.getType()) + && SchemaTypeUtil.PASSWORD_FORMAT.equals(schema.getFormat())) { // double + return true; + } + return false; + } + + public static boolean isByteArraySchema(Schema schema) { + if (schema instanceof ByteArraySchema) { + return true; + } + if (SchemaTypeUtil.STRING_TYPE.equals(schema.getType()) + && SchemaTypeUtil.BYTE_FORMAT.equals(schema.getFormat())) { // format: byte + return true; + } + return false; + } + + public static boolean isBinarySchema(Schema schema) { + if (schema instanceof BinarySchema) { + return true; + } + if (SchemaTypeUtil.STRING_TYPE.equals(schema.getType()) + && SchemaTypeUtil.BINARY_FORMAT.equals(schema.getFormat())) { // format: binary + return true; + } + return false; + } + + public static boolean isFileSchema(Schema schema) { + if (schema instanceof FileSchema) { + return true; + } + // file type in oas2 mapped to binary in oas3 + return isBinarySchema(schema); + } + + public static boolean isUUIDSchema(Schema schema) { + if (schema instanceof UUIDSchema) { + return true; + } + if (SchemaTypeUtil.STRING_TYPE.equals(schema.getType()) + && SchemaTypeUtil.UUID_FORMAT.equals(schema.getFormat())) { // format: uuid + return true; + } + return false; + } + + public static boolean isEmailSchema(Schema schema) { + if (schema instanceof EmailSchema) { + return true; + } + if (SchemaTypeUtil.STRING_TYPE.equals(schema.getType()) + && SchemaTypeUtil.EMAIL_FORMAT.equals(schema.getFormat())) { // format: email + return true; + } + return false; + } + + public static Schema getSchema(OpenAPI openapi, String name) { + if (name == null) { + return null; + } + + if (openapi != null && openapi.getComponents() != null && openapi.getComponents().getSchemas() != null) { + return openapi.getComponents().getSchemas().get(name); + } + + return null; + } + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/URLPathUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/URLPathUtils.java new file mode 100644 index 000000000000..654bbf4af8cf --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/URLPathUtils.java @@ -0,0 +1,59 @@ +package org.openapitools.codegen.utils; + +import org.openapitools.codegen.CodegenConfig; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.servers.Server; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; + +public class URLPathUtils { + + protected static final Logger LOGGER = LoggerFactory.getLogger(URLPathUtils.class); + public static String DEFAULT_PATH = "/"; + public static final String LOCAL_HOST = "http://localhost"; + + public static URL getServerURL(OpenAPI openAPI) { + final List servers = openAPI.getServers(); + if (servers == null || servers.isEmpty()) { + return null; + } + // TOOD need a way to obtain all server URLs + final Server server = servers.get(0); + String url = server.getUrl(); + if (url.equals(DEFAULT_PATH)) { + url = LOCAL_HOST; + } + try { + return new URL(server.getUrl()); + } catch (MalformedURLException e) { + LOGGER.warn("Not valid URL: " + server.getUrl(), e); + return null; + } + } + + public static String getScheme(OpenAPI openAPI, CodegenConfig config) { + String scheme; + URL url = getServerURL(openAPI); + if (url != null) { + scheme = url.getProtocol(); + } else { + scheme = "https"; + } + if (config != null) { + scheme = config.escapeText(scheme); + } + return scheme; + } + + public static String getHost(OpenAPI openAPI){ + if (openAPI.getServers() != null && openAPI.getServers().size() > 0) { + return openAPI.getServers().get(0).getUrl(); + } + return LOCAL_HOST; + } + +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Ada/swagger.mustache b/modules/openapi-generator/src/main/resources/Ada/swagger.mustache index 0a7a20061553..7710186d9d5c 100644 --- a/modules/openapi-generator/src/main/resources/Ada/swagger.mustache +++ b/modules/openapi-generator/src/main/resources/Ada/swagger.mustache @@ -1 +1 @@ -{{{swagger-json}}} \ No newline at end of file +{{{openapi-json}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JMeter/api.mustache b/modules/openapi-generator/src/main/resources/JMeter/api.mustache index f0c67670e5d4..d421423b0617 100644 --- a/modules/openapi-generator/src/main/resources/JMeter/api.mustache +++ b/modules/openapi-generator/src/main/resources/JMeter/api.mustache @@ -6,24 +6,28 @@ false false - - - host - localhost - = - - - port - 8080 - = - - + + + threads + ${__P(threads,1)} + = + + + rampup + ${__P(rampup,1)} + = + + + duration + ${__P(duration,1)} + = + testCases ${__P(testCases,10)} @@ -67,13 +71,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -109,7 +113,7 @@ false true false - HttpClient3.1 + false {{summary}} {{notes}} @@ -121,9 +125,10 @@ ${testData.{{operationId}}File} true true - shareMode.all + shareMode.group false + true diff --git a/modules/openapi-generator/src/main/resources/Java/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/build.gradle.mustache index cbc39ce3aca3..af0d3d55d85e 100644 --- a/modules/openapi-generator/src/main/resources/Java/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/build.gradle.mustache @@ -122,13 +122,13 @@ dependencies { compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" {{#joda}} - compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version", + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" {{/joda}} {{#java8}} - compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version", + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" {{/java8}} {{#threetenbp}} - compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_version", + compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_version" {{/threetenbp}} {{^java8}} compile "com.brsanthu:migbase64:2.2" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/formParams.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/formParams.mustache index f1f9027ae516..851072b3f653 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") TypedFile {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") TypedFile {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/formParams.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/formParams.mustache index b3f54cc4ddb3..f85b028870c9 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}} MultipartBody.Part {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}} MultipartBody.Part {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/formParams.mustache.save b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/formParams.mustache.save index 84c4704432ac..a3a3c16f1c07 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/formParams.mustache.save +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/formParams.mustache.save @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{#isMultipart}}retrofit.http@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}} okhttp3.MultipartBody.Part {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}{{#isMultipart}}retrofit.http@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}} okhttp3.MultipartBody.Part {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Java/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/pojo.mustache index 5bbeef075ba5..03b0f666d3e0 100644 --- a/modules/openapi-generator/src/main/resources/Java/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/pojo.mustache @@ -67,6 +67,19 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela {{/isContainer}} {{/vars}} + {{#parcelableModel}} + public {{classname}}() { + {{#parent}} + super(); + {{/parent}} + {{#gson}} + {{#discriminator}} + this.{{discriminator}} = this.getClass().getSimpleName(); + {{/discriminator}} + {{/gson}} + } + {{/parcelableModel}} + {{^parcelableModel}} {{#gson}} {{#discriminator}} public {{classname}}() { @@ -74,6 +87,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela } {{/discriminator}} {{/gson}} + {{/parcelableModel}} {{#vars}} {{^isReadOnly}} public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { @@ -203,27 +217,41 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela return o.toString().replace("\n", "\n "); } - {{#parcelableModel}} +{{#parcelableModel}} + public void writeToParcel(Parcel out, int flags) { - {{#parent}} super.writeToParcel(out, flags); {{/parent}} {{#vars}} +{{#model}} +{{#isArrayModel}} + out.writeList(this); +{{/isArrayModel}} +{{^isArrayModel}} +{{#parent}} + super.writeToParcel(out, flags); +{{/parent}} +{{#vars}} out.writeValue({{name}}); - {{/vars}} - } - - public {{classname}}() { - super(); +{{/vars}} +{{/isArrayModel}} +{{/model}} } {{classname}}(Parcel in) { - {{#parent}} super(in); {{/parent}} - {{#vars}} - {{#isPrimitiveType}} +{{#isArrayModel}} + in.readTypedList(this, {{arrayModelType}}.CREATOR); +{{/isArrayModel}} +{{^isArrayModel}} +{{#parent}} + super(in); +{{/parent}} +{{#vars}} +{{#isPrimitiveType}} {{name}} = ({{{datatypeWithEnum}}})in.readValue(null); - {{/isPrimitiveType}} - {{^isPrimitiveType}} +{{/isPrimitiveType}} +{{^isPrimitiveType}} {{name}} = ({{{datatypeWithEnum}}})in.readValue({{complexType}}.class.getClassLoader()); - {{/isPrimitiveType}} - {{/vars}} +{{/isPrimitiveType}} +{{/vars}} +{{/isArrayModel}} } public int describeContents() { @@ -232,11 +260,20 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela public static final Parcelable.Creator<{{classname}}> CREATOR = new Parcelable.Creator<{{classname}}>() { public {{classname}} createFromParcel(Parcel in) { +{{#model}} +{{#isArrayModel}} + {{classname}} result = new {{classname}}(); + result.addAll(in.readArrayList({{arrayModelType}}.class.getClassLoader())); + return result; +{{/isArrayModel}} +{{^isArrayModel}} return new {{classname}}(in); +{{/isArrayModel}} +{{/model}} } public {{classname}}[] newArray(int size) { return new {{classname}}[size]; } }; - {{/parcelableModel}} +{{/parcelableModel}} } diff --git a/modules/openapi-generator/src/main/resources/JavaInflector/formParams.mustache b/modules/openapi-generator/src/main/resources/JavaInflector/formParams.mustache index e44ab167e8f3..100c391f8ebc 100644 --- a/modules/openapi-generator/src/main/resources/JavaInflector/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaInflector/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}{{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaInflector/openapi.mustache b/modules/openapi-generator/src/main/resources/JavaInflector/openapi.mustache new file mode 100644 index 000000000000..51ebafb0187d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaInflector/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaInflector/swagger.mustache b/modules/openapi-generator/src/main/resources/JavaInflector/swagger.mustache deleted file mode 100644 index 51560926bba1..000000000000 --- a/modules/openapi-generator/src/main/resources/JavaInflector/swagger.mustache +++ /dev/null @@ -1 +0,0 @@ -{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/README.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/README.mustache index b8a8abc32ad0..8a5b690f9d04 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/README.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/README.mustache @@ -16,7 +16,7 @@ mvn clean package jetty:run You can then view the swagger listing here: ``` -http://localhost:{{serverPort}}{{contextPath}}/swagger.json +http://localhost:{{serverPort}}{{contextPath}}/openapi.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/cxf-cdi/formParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/formParams.mustache index 3721c1e80cab..d842b9dacd55 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}@Multipart(value = "{{baseName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{baseName}}"{{^required}}, required = false{{/required}}) InputStream {{paramName}}InputStream, @Multipart(value = "{{baseName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}@Multipart(value = "{{baseName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}} @Multipart(value = "{{baseName}}"{{^required}}, required = false{{/required}}) InputStream {{paramName}}InputStream, @Multipart(value = "{{baseName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/serviceFormParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/serviceFormParams.mustache index a7a154a9822f..df6fba4a3ddd 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/serviceFormParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/serviceFormParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream {{paramName}}InputStream, Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}{{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}InputStream {{paramName}}InputStream, Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/formParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/formParams.mustache index 70bbe6409fda..97216dc1806f 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}@Multipart(value = "{{baseName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{baseName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}@Multipart(value = "{{baseName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}} @Multipart(value = "{{baseName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/formParamsImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/formParamsImpl.mustache index e8c0e77c156e..2be40e1ddd3d 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/formParamsImpl.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/formParamsImpl.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}{{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}} Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/model.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/model.mustache index 0030cf7dd0c8..dd069aa87b38 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/model.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/model.mustache @@ -4,6 +4,7 @@ package {{package}}; {{/imports}} {{#useBeanValidation}} import javax.validation.constraints.*; +import javax.validation.Valid; {{/useBeanValidation}} {{#models}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pojo.mustache index b3817e2c81f9..860586410346 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -31,10 +31,11 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#withXml}} @XmlElement(name="{{baseName}}"{{#required}}, required = {{required}}{{/required}}) {{/withXml}} - @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}"){{^isPrimitiveType}}{{^isDate}}{{^isDateTime}}{{^isString}}{{^isFile}}{{#useBeanValidation}} + @Valid{{/useBeanValidation}}{{/isFile}}{{/isString}}{{/isDateTime}}{{/isDate}}{{/isPrimitiveType}} {{#description}} /** - * {{{description}}} + * {{{description}}} **/ {{/description}} {{#isContainer}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/server/readme.md b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/server/readme.md index 0f26af221276..60afd53a0df3 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/server/readme.md +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/server/readme.md @@ -17,7 +17,7 @@ http://localhost:8080/ * Swagger API - http://localhost:8080/services/swagger.json + http://localhost:8080/services/openapi.json * CXF WADL http://localhost:8080/services?_wadl diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/formParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/formParams.mustache index c57c57cd391b..b80ad9643a16 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/formParams.mustache @@ -1,3 +1,3 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}} {{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}} +{{#isFormParam}}{{^isFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}} {{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/isFile}}{{#isFile}} @FormDataParam("{{baseName}}") InputStream {{paramName}}InputStream, @FormDataParam("{{baseName}}") FormDataContentDisposition {{paramName}}Detail{{/isFile}}{{/isFormParam}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache index bc59f3bf873e..4b54a8d38d96 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache @@ -1,2 +1,2 @@ -{{#isFormParam}}{{#notFile}}{{^vendorExtensions.x-multipart}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/vendorExtensions.x-multipart}}{{#vendorExtensions.x-multipart}}@FormDataParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}} {{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}}@FormDataParam("{{baseName}}") InputStream inputStream, +{{#isFormParam}}{{^isFile}}{{^vendorExtensions.x-multipart}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/vendorExtensions.x-multipart}}{{#vendorExtensions.x-multipart}}@FormDataParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}} {{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/isFile}}{{#isFile}}@FormDataParam("{{baseName}}") InputStream inputStream, @FormDataParam("{{baseName}}") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file 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 3551b9e99149..b527625484e0 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/README.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/README.mustache @@ -16,7 +16,7 @@ mvn clean package jetty:run You can then view the swagger listing here: ``` -http://localhost:{{serverPort}}{{contextPath}}/swagger.json +http://localhost:{{serverPort}}{{contextPath}}/openapi.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 a0396fc36118..ee8d22236c57 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 @@ -12,7 +12,7 @@ You can deploy the WAR file to Jboss EAP or any other JEE server supporting Jbos You can then view the swagger listing here: ``` -http://localhost:{{serverPort}}{{contextPath}}/swagger.json +http://localhost:{{serverPort}}{{contextPath}}/openapi.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/formParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/formParams.mustache index 04f6ed275c8d..d26654e27887 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/serviceFormParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/serviceFormParams.mustache index e44ab167e8f3..100c391f8ebc 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/serviceFormParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/serviceFormParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}{{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/formParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/formParams.mustache index 04f6ed275c8d..d26654e27887 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/serviceFormParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/serviceFormParams.mustache index e44ab167e8f3..100c391f8ebc 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/serviceFormParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/serviceFormParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}{{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/serviceFormParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/serviceFormParams.mustache index dc2d2eb1ecf2..b4b46dc7a42d 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/serviceFormParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/serviceFormParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream {{paramName}}InputStream, FormDataContentDisposition {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}{{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}InputStream {{paramName}}InputStream, FormDataContentDisposition {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/formParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/formParams.mustache index 931d1abff8b8..cf4550833386 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/formParams.mustache @@ -1,2 +1,2 @@ -{{#isFormParam}}{{#notFile}}@FormParam(value = "{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @FormParam(value = "{{baseName}}") InputStream {{paramName}}InputStream, +{{#isFormParam}}{{^isFile}}@FormParam(value = "{{baseName}}") {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}} @FormParam(value = "{{baseName}}") InputStream {{paramName}}InputStream, @FormParam(value = "{{baseName}}") Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/openapi.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/openapi.mustache new file mode 100644 index 000000000000..51ebafb0187d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaPlayFramework/apiDocController.mustache b/modules/openapi-generator/src/main/resources/JavaPlayFramework/apiDocController.mustache index 8985d9fba8bc..b54be6d8e6a3 100644 --- a/modules/openapi-generator/src/main/resources/JavaPlayFramework/apiDocController.mustache +++ b/modules/openapi-generator/src/main/resources/JavaPlayFramework/apiDocController.mustache @@ -10,6 +10,6 @@ public class ApiDocController extends Controller { } public Result api() { - return redirect("/assets/lib/swagger-ui/index.html?/url=/assets/swagger.json"); + return redirect("/assets/lib/swagger-ui/index.html?/url=/assets/openapi.json"); } } diff --git a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApi.mustache b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApi.mustache index 6862b7402a33..7355eae845c6 100644 --- a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApi.mustache +++ b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApi.mustache @@ -16,15 +16,21 @@ import javax.validation.constraints.*; public class {{classname}}ControllerImp {{#useInterfaces}}implements {{classname}}ControllerImpInterface{{/useInterfaces}} { {{#operation}} {{#useInterfaces}}@Override{{/useInterfaces}} - public {{>returnTypes}} {{operationId}}({{#allParams}}{{>pathParams}}{{>queryParams}}{{>bodyParams}}{{>formParams}}{{>headerParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#handleExceptions}}throws Exception{{/handleExceptions}} { + public {{^returnType}}void{{/returnType}}{{#returnType}}{{#supportAsync}}CompletionStage<{{/supportAsync}}{{>returnTypesNoVoid}}{{#supportAsync}}>{{/supportAsync}}{{/returnType}} {{operationId}}({{#allParams}}{{>pathParams}}{{>queryParams}}{{>bodyParams}}{{>formParams}}{{>headerParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#handleExceptions}}throws Exception{{/handleExceptions}} { //Do your magic!!! {{#returnType}} + {{#supportAsync}} + return CompletableFuture.supplyAsync(() -> { + {{/supportAsync}} {{#isResponseFile}} return new FileInputStream("replace this"); {{/isResponseFile}} {{^isResponseFile}} - return new {{>returnTypesNoVoidNoAbstract}}({{#vendorExtensions.missingReturnInfoIfNeeded}}{{vendorExtensions.missingReturnInfoIfNeeded}}{{/vendorExtensions.missingReturnInfoIfNeeded}}); + {{#supportAsync}} {{/supportAsync}}return new {{>returnTypesNoVoidNoAbstract}}({{#vendorExtensions.missingReturnInfoIfNeeded}}{{vendorExtensions.missingReturnInfoIfNeeded}}{{/vendorExtensions.missingReturnInfoIfNeeded}}); {{/isResponseFile}} + {{#supportAsync}} + }); + {{/supportAsync}} {{/returnType}} } diff --git a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiController.mustache b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiController.mustache index 906dbd59b8ae..2c2bb8985489 100644 --- a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiController.mustache +++ b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiController.mustache @@ -18,6 +18,11 @@ import java.io.IOException; {{/handleExceptions}} import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; +{{#supportAsync}} + +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; +{{/supportAsync}} {{#useBeanValidation}} import javax.validation.constraints.*; @@ -54,7 +59,7 @@ public class {{classname}}Controller extends Controller { {{#operation}} {{#wrapCalls}}@ApiAction{{/wrapCalls}} - public Result {{operationId}}({{#pathParams}}{{>pathParams}}{{#hasMore}},{{/hasMore}}{{/pathParams}}) {{^handleExceptions}}{{#bodyParams}}throws IOException{{/bodyParams}}{{/handleExceptions}}{{#handleExceptions}}throws Exception{{/handleExceptions}} { + public {{#supportAsync}}CompletionStage<{{/supportAsync}}Result{{#supportAsync}}>{{/supportAsync}} {{operationId}}({{#pathParams}}{{>pathParams}}{{#hasMore}},{{/hasMore}}{{/pathParams}}) {{^handleExceptions}}{{#bodyParams}}throws IOException{{/bodyParams}}{{/handleExceptions}}{{#handleExceptions}}throws Exception{{/handleExceptions}} { {{#bodyParams}} {{^collectionFormat}} JsonNode node{{paramName}} = request().body().asJson(); @@ -121,15 +126,15 @@ public class {{classname}}Controller extends Controller { {{/collectionFormat}} {{/queryParams}} {{#formParams}} - {{^notFile}} + {{#isFile}} {{{dataType}}} {{paramName}} = request().body().asMultipartFormData().getFile("{{baseName}}"); {{#required}} if (({{paramName}} == null || ((File) {{paramName}}.getFile()).length() == 0)) { throw new IllegalArgumentException("'{{baseName}}' file cannot be empty"); } {{/required}} - {{/notFile}} - {{#notFile}} + {{/isFile}} + {{^isFile}} {{#collectionFormat}} String[] {{paramName}}Array = request().body().asMultipartFormData().asFormUrlEncoded().get("{{baseName}}"); {{#required}} @@ -160,7 +165,7 @@ public class {{classname}}Controller extends Controller { {{/required}} } {{/collectionFormat}} - {{/notFile}} + {{/isFile}} {{/formParams}} {{#headerParams}} {{#collectionFormat}} @@ -195,11 +200,17 @@ public class {{classname}}Controller extends Controller { {{/collectionFormat}} {{/headerParams}} {{^controllerOnly}} - {{#returnType}}{{>returnTypesNoVoid}} obj = {{/returnType}}imp.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{^returnType}} + {{#supportAsync}} + return CompletableFuture.supplyAsync(() -> { + {{/supportAsync}} + {{/returnType}} + {{#returnType}}{{#supportAsync}}CompletionStage<{{>returnTypesNoVoid}}> stage = {{/supportAsync}}{{^supportAsync}}{{>returnTypesNoVoid}} obj = {{/supportAsync}}{{/returnType}}{{^returnType}}{{#supportAsync}} {{/supportAsync}}{{/returnType}}imp.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}{{#supportAsync}}.thenApply(obj -> { {{/supportAsync}}{{/returnType}}{{^supportAsync}};{{/supportAsync}} {{#returnType}} {{^isResponseFile}} {{^returnTypeIsPrimitive}} {{#useBeanValidation}} + {{^supportAsync}} if (configuration.getBoolean("useOutputBeanValidation")) { {{#isListContainer}} for ({{{returnType}}} curItem : obj) { @@ -215,21 +226,50 @@ public class {{classname}}Controller extends Controller { SwaggerUtils.validate(obj); {{/returnContainer}} } + {{/supportAsync}} + {{#supportAsync}} + if (configuration.getBoolean("useOutputBeanValidation")) { + {{#isListContainer}} + for ({{{returnType}}} curItem : obj) { + SwaggerUtils.validate(curItem); + } + {{/isListContainer}} + {{#isMapContainer}} + for (Map.Entry entry : obj.entrySet()) { + SwaggerUtils.validate(entry.getValue()); + } + {{/isMapContainer}} + {{^returnContainer}} + SwaggerUtils.validate(obj); + {{/returnContainer}} + } + {{/supportAsync}} {{/useBeanValidation}} {{/returnTypeIsPrimitive}} {{/isResponseFile}} + {{#supportAsync}} + return obj; + }); + {{/supportAsync}} {{/returnType}} {{#returnType}} - {{^isResponseFile}}JsonNode result = mapper.valueToTree(obj); - return ok(result); + {{#supportAsync}} + stage.thenApply(obj -> { + {{/supportAsync}} + {{^isResponseFile}} + {{#supportAsync}} {{/supportAsync}}JsonNode result = mapper.valueToTree(obj); + {{#supportAsync}} {{/supportAsync}}return ok(result); {{/isResponseFile}} {{#isResponseFile}} - return ok(obj); + {{#supportAsync}} {{/supportAsync}}return ok(obj); {{/isResponseFile}} {{/returnType}} {{^returnType}} - return ok(); + {{#supportAsync}} {{/supportAsync}}return ok(); {{/returnType}} + {{#supportAsync}} + }); + {{/supportAsync}} {{/controllerOnly}} {{#controllerOnly}} return ok(); diff --git a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiInterface.mustache b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiInterface.mustache index 918ee1f85b1f..0b60e57db9d9 100644 --- a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiInterface.mustache +++ b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiInterface.mustache @@ -7,6 +7,10 @@ import play.mvc.Http; import java.util.List; import java.util.ArrayList; import java.util.HashMap; +{{#supportAsync}} +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; +{{/supportAsync}} {{#useBeanValidation}} import javax.validation.constraints.*; @@ -16,7 +20,7 @@ import javax.validation.constraints.*; @SuppressWarnings("RedundantThrows") public interface {{classname}}ControllerImpInterface { {{#operation}} - {{>returnTypes}} {{operationId}}({{#allParams}}{{>pathParams}}{{>queryParams}}{{>bodyParams}}{{>formParams}}{{>headerParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#handleExceptions}}throws Exception{{/handleExceptions}}; + {{^returnType}}void{{/returnType}}{{#returnType}}{{#supportAsync}}CompletionStage<{{/supportAsync}}{{>returnTypesNoVoid}}{{#supportAsync}}>{{/supportAsync}}{{/returnType}} {{operationId}}({{#allParams}}{{>pathParams}}{{>queryParams}}{{>bodyParams}}{{>formParams}}{{>headerParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#handleExceptions}}throws Exception{{/handleExceptions}}; {{/operation}} } diff --git a/modules/openapi-generator/src/main/resources/JavaPlayFramework/swagger.mustache b/modules/openapi-generator/src/main/resources/JavaPlayFramework/swagger.mustache index 0a7a20061553..7710186d9d5c 100644 --- a/modules/openapi-generator/src/main/resources/JavaPlayFramework/swagger.mustache +++ b/modules/openapi-generator/src/main/resources/JavaPlayFramework/swagger.mustache @@ -1 +1 @@ -{{{swagger-json}}} \ No newline at end of file +{{{openapi-json}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/formParams.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/formParams.mustache index 7305792be1fa..e737e3f8b1e9 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value="{{baseName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value="{{baseName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}@ApiParam(value = "file detail") {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/formParams.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/formParams.mustache index bd2cb8bb6409..cce76eecb207 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value="{{baseName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestParam("{{baseName}}") MultipartFile {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value="{{baseName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestParam("{{baseName}}") MultipartFile {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaVertXServer/MainApiVerticle.mustache b/modules/openapi-generator/src/main/resources/JavaVertXServer/MainApiVerticle.mustache index 050cb6d57ebe..cf89b1436bb5 100644 --- a/modules/openapi-generator/src/main/resources/JavaVertXServer/MainApiVerticle.mustache +++ b/modules/openapi-generator/src/main/resources/JavaVertXServer/MainApiVerticle.mustache @@ -42,7 +42,7 @@ public class MainApiVerticle extends AbstractVerticle { public void start(Future startFuture) throws Exception { Json.mapper.registerModule(new JavaTimeModule()); FileSystem vertxFileSystem = vertx.fileSystem(); - vertxFileSystem.readFile("swagger.json", readFile -> { + vertxFileSystem.readFile("openapi.json", readFile -> { if (readFile.succeeded()) { Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8"))); Router swaggerRouter = SwaggerRouter.swaggerRouter(router, swagger, vertx.eventBus(), new OperationIdServiceIdResolver()); diff --git a/modules/openapi-generator/src/main/resources/JavaVertXServer/swagger.mustache b/modules/openapi-generator/src/main/resources/JavaVertXServer/swagger.mustache index d54f6b94d2b3..e5799e4d042f 100644 --- a/modules/openapi-generator/src/main/resources/JavaVertXServer/swagger.mustache +++ b/modules/openapi-generator/src/main/resources/JavaVertXServer/swagger.mustache @@ -1 +1 @@ -{{{fullSwagger}}} \ No newline at end of file +{{{fullOpenAPI}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Javascript/README.mustache b/modules/openapi-generator/src/main/resources/Javascript/README.mustache index 4962803a76f0..9ec9d7bed521 100644 --- a/modules/openapi-generator/src/main/resources/Javascript/README.mustache +++ b/modules/openapi-generator/src/main/resources/Javascript/README.mustache @@ -120,15 +120,23 @@ var {{{name}}} = defaultClient.authentications['{{{name}}}']; {{/authMethods}} {{/hasAuthMethods}} -var api = new {{{moduleName}}}.{{{classname}}}(){{#hasParams}} -{{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} +var api = new {{{moduleName}}}.{{{classname}}}() +{{#hasParams}} +{{#requiredParams}} var {{{paramName}}} = {{{example}}}; // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}} -{{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} -var opts = { {{#allParams}}{{^required}} - '{{{paramName}}}': {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}}{{/required}}{{/allParams}} -};{{/hasOptionalParams}}{{/hasParams}} +{{/requiredParams}} +{{#optionalParams}} +{{#-first}} +var opts = { +{{/-first}} + '{{{paramName}}}': {{{example}}}{{^-last}},{{/-last}} // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}} +{{#-last}} +}; +{{/-last}} +{{/optionalParams}} +{{/hasParams}} {{#usePromises}} -api.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}).then(function({{#returnType}}data{{/returnType}}) { +api.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}).then(function({{#returnType}}data{{/returnType}}) { {{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} }, function(error) { console.error(error); @@ -142,7 +150,7 @@ var callback = function(error, data, response) { {{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} } }; -api.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}{{#hasParams}}, {{/hasParams}}callback); +api.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}{{#hasParams}}, {{/hasParams}}callback); {{/usePromises}}{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} ``` diff --git a/modules/openapi-generator/src/main/resources/Javascript/api_doc.mustache b/modules/openapi-generator/src/main/resources/Javascript/api_doc.mustache index 686f23b49a0a..7506b091bdea 100644 --- a/modules/openapi-generator/src/main/resources/Javascript/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/Javascript/api_doc.mustache @@ -12,7 +12,7 @@ Method | HTTP request | Description {{#operation}} # **{{operationId}}** -> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}) +> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}) {{summary}}{{#notes}} @@ -27,33 +27,45 @@ var defaultClient = {{{moduleName}}}.ApiClient.instance; // Configure HTTP basic authorization: {{{name}}} var {{{name}}} = defaultClient.authentications['{{{name}}}']; {{{name}}}.username = 'YOUR USERNAME'; -{{{name}}}.password = 'YOUR PASSWORD';{{/isBasic}}{{#isApiKey}} +{{{name}}}.password = 'YOUR PASSWORD'; +{{/isBasic}} +{{#isApiKey}} // Configure API key authorization: {{{name}}} var {{{name}}} = defaultClient.authentications['{{{name}}}']; {{{name}}}.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) -//{{{name}}}.apiKeyPrefix = 'Token';{{/isApiKey}}{{#isOAuth}} +//{{{name}}}.apiKeyPrefix = 'Token'; +{{/isApiKey}} +{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} var {{{name}}} = defaultClient.authentications['{{{name}}}']; -{{{name}}}.accessToken = 'YOUR ACCESS TOKEN';{{/isOAuth}} +{{{name}}}.accessToken = 'YOUR ACCESS TOKEN'; +{{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} -var apiInstance = new {{{moduleName}}}.{{{classname}}}();{{#hasParams}} -{{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} +var apiInstance = new {{{moduleName}}}.{{{classname}}}(); +{{#requiredParams}} var {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} -{{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} -var opts = { {{#allParams}}{{^required}} - '{{{paramName}}}': {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} // {{{dataType}}} | {{{description}}}{{/required}}{{/allParams}} -};{{/hasOptionalParams}}{{/hasParams}} +{{/requiredParams}} +{{#optionalParams}} +{{#-first}} +var opts = { +{{/-first}} + '{{{paramName}}}': {{{example}}}{{^-last}},{{/-last}} // {{{dataType}}} | {{{description}}} +{{#-last}} +}; +{{/-last}} +{{/optionalParams}} {{#usePromises}} -apiInstance.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}).then(function({{#returnType}}data{{/returnType}}) { +apiInstance.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}).then(function({{#returnType}}data{{/returnType}}) { {{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} }, function(error) { console.error(error); }); -{{/usePromises}}{{^usePromises}} +{{/usePromises}} +{{^usePromises}} var callback = function(error, data, response) { if (error) { console.error(error); @@ -61,7 +73,7 @@ var callback = function(error, data, response) { {{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} } }; -apiInstance.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}{{#hasParams}}, {{/hasParams}}callback); +apiInstance.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}{{#hasParams}}, {{/hasParams}}callback); {{/usePromises}} ``` diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/README.mustache b/modules/openapi-generator/src/main/resources/Javascript/es6/README.mustache index c13314a89605..16b849d32d80 100644 --- a/modules/openapi-generator/src/main/resources/Javascript/es6/README.mustache +++ b/modules/openapi-generator/src/main/resources/Javascript/es6/README.mustache @@ -77,39 +77,55 @@ Please follow the [installation](#installation) instruction and execute the foll ```javascript var {{{moduleName}}} = require('{{{projectName}}}'); -{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}} +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +{{#hasAuthMethods}} var defaultClient = {{{moduleName}}}.ApiClient.instance; -{{#authMethods}}{{#isBasic}} +{{#authMethods}} +{{#isBasic}} // Configure HTTP basic authorization: {{{name}}} var {{{name}}} = defaultClient.authentications['{{{name}}}']; {{{name}}}.username = 'YOUR USERNAME' -{{{name}}}.password = 'YOUR PASSWORD'{{/isBasic}}{{#isApiKey}} +{{{name}}}.password = 'YOUR PASSWORD' +{{/isBasic}} +{{#isApiKey}} // Configure API key authorization: {{{name}}} var {{{name}}} = defaultClient.authentications['{{{name}}}']; {{{name}}}.apiKey = "YOUR API KEY" // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) -//{{{name}}}.apiKeyPrefix['{{{keyParamName}}}'] = "Token"{{/isApiKey}}{{#isOAuth}} +//{{{name}}}.apiKeyPrefix['{{{keyParamName}}}'] = "Token" +{{/isApiKey}} +{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} var {{{name}}} = defaultClient.authentications['{{{name}}}']; -{{{name}}}.accessToken = "YOUR ACCESS TOKEN"{{/isOAuth}} +{{{name}}}.accessToken = "YOUR ACCESS TOKEN" +{{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} -var api = new {{{moduleName}}}.{{{classname}}}(){{#hasParams}} -{{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} +var api = new {{{moduleName}}}.{{{classname}}}() +{{#hasParams}} +{{#requiredParams}} var {{{paramName}}} = {{{example}}}; // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}} -{{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} -var opts = { {{#allParams}}{{^required}} - '{{{paramName}}}': {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}}{{/required}}{{/allParams}} -};{{/hasOptionalParams}}{{/hasParams}} +{{/requiredParams}} +{{#optionalParams}} +{{#-first}} +var opts = { +{{/-first}} + '{{{paramName}}}': {{{example}}}{{^-last}},{{/-last}} // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}} +{{#-last}} +}; +{{/-last}} +{{/optionalParams}} +{{/hasParams}} {{#usePromises}} -api.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}).then(function({{#returnType}}data{{/returnType}}) { +api.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}).then(function({{#returnType}}data{{/returnType}}) { {{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} }, function(error) { console.error(error); }); -{{/usePromises}}{{^usePromises}} +{{/usePromises}} +{{^usePromises}} var callback = function(error, data, response) { if (error) { console.error(error); @@ -117,8 +133,9 @@ var callback = function(error, data, response) { {{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} } }; -api.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}{{#hasParams}}, {{/hasParams}}callback); -{{/usePromises}}{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +api.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}{{#hasParams}}, {{/hasParams}}callback); +{{/usePromises}} +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} ``` ## Documentation for API Endpoints diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/api_doc.mustache b/modules/openapi-generator/src/main/resources/Javascript/es6/api_doc.mustache index eb0f2e36ce89..c041b5ffaeb7 100644 --- a/modules/openapi-generator/src/main/resources/Javascript/es6/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/Javascript/es6/api_doc.mustache @@ -12,7 +12,7 @@ Method | HTTP request | Description {{#operation}} # **{{operationId}}** -> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}) +> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}) {{summary}}{{#notes}} @@ -39,22 +39,29 @@ let {{{name}}} = defaultClient.authentications['{{{name}}}']; {{/authMethods}} {{/hasAuthMethods}} -let apiInstance = new {{{moduleName}}}.{{{classname}}}();{{#hasParams}} -{{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} +let apiInstance = new {{{moduleName}}}.{{{classname}}}(); +{{#requiredParams}} let {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} -{{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} -let opts = { {{#allParams}}{{^required}} - '{{{paramName}}}': {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} // {{{dataType}}} | {{{description}}}{{/required}}{{/allParams}} -};{{/hasOptionalParams}}{{/hasParams}} +{{/requiredParams}} +{{#optionalParams}} +{{#-first}} +let opts = { +{{/-first}} + '{{{paramName}}}': {{{example}}}{{^-last}},{{/-last}} // {{{dataType}}} | {{{description}}} +{{#-last}} +}; +{{/-last}} +{{/optionalParams}} {{#usePromises}} -apiInstance.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}).then(({{#returnType}}data{{/returnType}}) => { +apiInstance.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}).then(({{#returnType}}data{{/returnType}}) => { {{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} }, (error) => { console.error(error); }); -{{/usePromises}}{{^usePromises}} -apiInstance.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}{{#hasParams}}, {{/hasParams}}(error, data, response) => { +{{/usePromises}} +{{^usePromises}} +apiInstance.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}{{#hasParams}}, {{/hasParams}}(error, data, response) => { if (error) { console.error(error); } else { 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 5d56ab2f67de..67c3f390a373 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 @@ -1,90 +1,90 @@ org.openapitools.codegen.languages.AdaCodegen org.openapitools.codegen.languages.AdaServerCodegen -org.openapitools.codegen.languages.AkkaScalaClientCodegen org.openapitools.codegen.languages.AndroidClientCodegen +org.openapitools.codegen.languages.AkkaScalaClientCodegen org.openapitools.codegen.languages.Apache2ConfigCodegen org.openapitools.codegen.languages.ApexClientCodegen org.openapitools.codegen.languages.AspNetCoreServerCodegen org.openapitools.codegen.languages.BashClientCodegen -org.openapitools.codegen.languages.CSharpClientCodegen org.openapitools.codegen.languages.ClojureClientCodegen -org.openapitools.codegen.languages.ConfluenceWikiGenerator +org.openapitools.codegen.languages.ConfluenceWikiCodegen +org.openapitools.codegen.languages.CppQt5ClientCodegen +org.openapitools.codegen.languages.CppPistacheServerCodegen +org.openapitools.codegen.languages.CppRestbedServerCodegen org.openapitools.codegen.languages.CppRestClientCodegen -org.openapitools.codegen.languages.CsharpDotNet2ClientCodegen +org.openapitools.codegen.languages.CppTizenClientCodegen +org.openapitools.codegen.languages.CSharpClientCodegen +org.openapitools.codegen.languages.CSharpDotNet2ClientCodegen +org.openapitools.codegen.languages.CSharpNancyFXServerCodegen org.openapitools.codegen.languages.DartClientCodegen +org.openapitools.codegen.languages.EiffelClientCodegen org.openapitools.codegen.languages.ElixirClientCodegen org.openapitools.codegen.languages.ElmClientCodegen -org.openapitools.codegen.languages.EiffelClientCodegen org.openapitools.codegen.languages.ErlangClientCodegen org.openapitools.codegen.languages.ErlangServerCodegen -org.openapitools.codegen.languages.FinchServerCodegen org.openapitools.codegen.languages.FlashClientCodegen -org.openapitools.codegen.languages.FlaskConnexionCodegen +org.openapitools.codegen.languages.FinchServerCodegen org.openapitools.codegen.languages.GoClientCodegen org.openapitools.codegen.languages.GoServerCodegen org.openapitools.codegen.languages.GroovyClientCodegen +org.openapitools.codegen.languages.KotlinClientCodegen +org.openapitools.codegen.languages.KotlinServerCodegen org.openapitools.codegen.languages.HaskellHttpClientCodegen org.openapitools.codegen.languages.HaskellServantCodegen -org.openapitools.codegen.languages.JMeterCodegen -org.openapitools.codegen.languages.JavaCXFClientCodegen -org.openapitools.codegen.languages.JavaCXFServerCodegen org.openapitools.codegen.languages.JavaClientCodegen +org.openapitools.codegen.languages.JavaCXFClientCodegen org.openapitools.codegen.languages.JavaInflectorServerCodegen -org.openapitools.codegen.languages.JavaJAXRSCXFCDIServerCodegen -org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen -org.openapitools.codegen.languages.JavaJerseyServerCodegen -org.openapitools.codegen.languages.JavaJerseyServerCodegen org.openapitools.codegen.languages.JavaMSF4JServerCodegen org.openapitools.codegen.languages.JavaPKMSTServerCodegen org.openapitools.codegen.languages.JavaPlayFrameworkCodegen -org.openapitools.codegen.languages.JavaResteasyEapServerCodegen +org.openapitools.codegen.languages.JavaUndertowServerCodegen +org.openapitools.codegen.languages.JavaVertXServerCodegen +org.openapitools.codegen.languages.JavaCXFServerCodegen +org.openapitools.codegen.languages.JavaJAXRSCXFCDIServerCodegen +org.openapitools.codegen.languages.JavaJerseyServerCodegen org.openapitools.codegen.languages.JavaResteasyServerCodegen +org.openapitools.codegen.languages.JavaResteasyEapServerCodegen +org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen org.openapitools.codegen.languages.JavascriptClientCodegen org.openapitools.codegen.languages.JavascriptClosureAngularClientCodegen -org.openapitools.codegen.languages.JavaVertXServerCodegen -org.openapitools.codegen.languages.KotlinClientCodegen +org.openapitools.codegen.languages.JMeterCodegen org.openapitools.codegen.languages.LuaClientCodegen -org.openapitools.codegen.languages.LumenServerCodegen -org.openapitools.codegen.languages.NancyFXServerCodegen org.openapitools.codegen.languages.NodeJSServerCodegen org.openapitools.codegen.languages.ObjcClientCodegen +org.openapitools.codegen.languages.OpenAPIGenerator +org.openapitools.codegen.languages.OpenAPIYamlGenerator org.openapitools.codegen.languages.PerlClientCodegen org.openapitools.codegen.languages.PhpClientCodegen +org.openapitools.codegen.languages.PhpLumenServerCodegen +org.openapitools.codegen.languages.PhpSlimServerCodegen +org.openapitools.codegen.languages.PhpSilexServerCodegen +org.openapitools.codegen.languages.PhpSymfonyServerCodegen +org.openapitools.codegen.languages.PhpZendExpressivePathHandlerServerCodegen org.openapitools.codegen.languages.PowerShellClientCodegen -org.openapitools.codegen.languages.PistacheServerCodegen org.openapitools.codegen.languages.PythonClientCodegen -org.openapitools.codegen.languages.Qt5CPPGenerator +org.openapitools.codegen.languages.PythonFlaskConnexionServerCodegen org.openapitools.codegen.languages.RClientCodegen -org.openapitools.codegen.languages.Rails5ServerCodegen -org.openapitools.codegen.languages.RestbedCodegen org.openapitools.codegen.languages.RubyClientCodegen +org.openapitools.codegen.languages.RubyOnRailsServerCodegen +org.openapitools.codegen.languages.RubySinatraServerCodegen org.openapitools.codegen.languages.RustClientCodegen org.openapitools.codegen.languages.RustServerCodegen +org.openapitools.codegen.languages.ScalatraServerCodegen org.openapitools.codegen.languages.ScalaClientCodegen org.openapitools.codegen.languages.ScalaGatlingCodegen org.openapitools.codegen.languages.ScalaLagomServerCodegen -org.openapitools.codegen.languages.ScalatraServerCodegen org.openapitools.codegen.languages.ScalazClientCodegen -org.openapitools.codegen.languages.SilexServerCodegen -org.openapitools.codegen.languages.SinatraServerCodegen -org.openapitools.codegen.languages.SlimFrameworkServerCodegen org.openapitools.codegen.languages.SpringCodegen org.openapitools.codegen.languages.StaticDocCodegen -org.openapitools.codegen.languages.StaticHtml2Generator org.openapitools.codegen.languages.StaticHtmlGenerator -org.openapitools.codegen.languages.SwaggerGenerator -org.openapitools.codegen.languages.SwaggerYamlGenerator -org.openapitools.codegen.languages.Swift4Codegen +org.openapitools.codegen.languages.StaticHtml2Generator +org.openapitools.codegen.languages.SwiftClientCodegen org.openapitools.codegen.languages.Swift3Codegen -org.openapitools.codegen.languages.SwiftCodegen -org.openapitools.codegen.languages.SymfonyServerCodegen -org.openapitools.codegen.languages.TizenClientCodegen -org.openapitools.codegen.languages.TypeScriptAureliaClientCodegen +org.openapitools.codegen.languages.Swift4Codegen org.openapitools.codegen.languages.TypeScriptAngularClientCodegen org.openapitools.codegen.languages.TypeScriptAngularJsClientCodegen +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.UndertowCodegen -org.openapitools.codegen.languages.ZendExpressivePathHandlerServerCodegen -org.openapitools.codegen.languages.KotlinServerCodegen diff --git a/modules/openapi-generator/src/main/resources/MSF4J/formParams.mustache b/modules/openapi-generator/src/main/resources/MSF4J/formParams.mustache index 0a8a7225031c..f7d110045892 100644 --- a/modules/openapi-generator/src/main/resources/MSF4J/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/MSF4J/formParams.mustache @@ -1,3 +1,3 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}} {{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}} +{{#isFormParam}}{{^isFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}} {{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/isFile}}{{#isFile}} @FormDataParam("{{baseName}}") InputStream {{paramName}}InputStream, @FormDataParam("{{baseName}}") FileInfo {{paramName}}Detail{{/isFile}}{{/isFormParam}} diff --git a/modules/openapi-generator/src/main/resources/MSF4J/serviceFormParams.mustache b/modules/openapi-generator/src/main/resources/MSF4J/serviceFormParams.mustache index c58393551dfc..5e5b21e51aa2 100644 --- a/modules/openapi-generator/src/main/resources/MSF4J/serviceFormParams.mustache +++ b/modules/openapi-generator/src/main/resources/MSF4J/serviceFormParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream {{paramName}}InputStream, FileInfo {{paramName}}Detail{{/isFile}}{{/isFormParam}} +{{#isFormParam}}{{^isFile}}{{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}InputStream {{paramName}}InputStream, FileInfo {{paramName}}Detail{{/isFile}}{{/isFormParam}} diff --git a/modules/openapi-generator/src/main/resources/android/api.mustache b/modules/openapi-generator/src/main/resources/android/api.mustache index 44e96c63fc08..cf7d57ab4db5 100644 --- a/modules/openapi-generator/src/main/resources/android/api.mustache +++ b/modules/openapi-generator/src/main/resources/android/api.mustache @@ -83,11 +83,11 @@ public class {{classname}} { if (localVarContentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - {{#formParams}}{{#notFile}} + {{#formParams}}{{^isFile}} if ({{paramName}} != null) { localVarBuilder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8); } - {{/notFile}}{{#isFile}} + {{/isFile}}{{#isFile}} if ({{paramName}} != null) { localVarBuilder.addBinaryBody("{{baseName}}", {{paramName}}); } @@ -96,7 +96,7 @@ public class {{classname}} { localVarPostBody = localVarBuilder.build(); } else { // normal form params - {{#formParams}}{{#notFile}}localVarFormParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}} + {{#formParams}}{{^isFile}}localVarFormParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/isFile}} {{/formParams}} } diff --git a/modules/openapi-generator/src/main/resources/android/libraries/volley/api.mustache b/modules/openapi-generator/src/main/resources/android/libraries/volley/api.mustache index 97c7c92ce638..b1441e7cd65d 100644 --- a/modules/openapi-generator/src/main/resources/android/libraries/volley/api.mustache +++ b/modules/openapi-generator/src/main/resources/android/libraries/volley/api.mustache @@ -183,11 +183,11 @@ public class {{classname}} { if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - {{#formParams}}{{#notFile}} + {{#formParams}}{{^isFile}} if ({{paramName}} != null) { localVarBuilder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8); } - {{/notFile}}{{#isFile}} + {{/isFile}}{{#isFile}} if ({{paramName}} != null) { localVarBuilder.addBinaryBody("{{baseName}}", {{paramName}}); } @@ -197,7 +197,7 @@ public class {{classname}} { postBody = httpEntity; } else { // normal form params - {{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}} + {{#formParams}}{{^isFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/isFile}} {{/formParams}} } diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/Dockerfile.mustache index 553d5ce5ce99..e9d80c52833b 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/Dockerfile.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/Dockerfile.mustache @@ -1,11 +1,18 @@ -FROM microsoft/dotnet:1.0.3-sdk-projectjson +FROM microsoft/aspnetcore-build:2.0 AS build-env +WORKDIR /app ENV DOTNET_CLI_TELEMETRY_OPTOUT 1 -WORKDIR /app/{{packageName}} -COPY . /app/{{packageName}} +# copy csproj and restore as distinct layers +COPY *.csproj ./ +RUN dotnet restore -EXPOSE 5000/tcp +# copy everything else and build +COPY . ./ +RUN dotnet publish -c Release -o out -RUN ["dotnet", "restore"] -ENTRYPOINT ["dotnet", "run", "-p", "project.json", "web"] +# build runtime image +FROM microsoft/aspnetcore:2.0 +WORKDIR /app +COPY --from=build-env /app/out . +ENTRYPOINT ["dotnet", "{{packageName}}.dll"] diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/Startup.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/Startup.mustache index 5b95562dcdc8..a6b414f8e173 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/Startup.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/Startup.mustache @@ -62,7 +62,7 @@ namespace {{packageName}} Contact = new Contact() { Name = "{{#infoName}}{{{infoName}}}{{/infoName}}{{^infoName}}Swagger Codegen Contributors{{/infoName}}", - Url = "{{#infoUrl}}{{{infoUrl}}}{{/infoUrl}}{{^infoUrl}}https://github.com/swagger-api/swagger-codegen{{/infoUrl}}", + Url = "{{#infoUrl}}{{{infoUrl}}}{{/infoUrl}}{{^infoUrl}}https://github.com/openapitools/openapi-generator{{/infoUrl}}", Email = "{{#infoEmail}}{{{infoEmail}}}{{/infoEmail}}" }, TermsOfService = "{{#termsOfService}}{{{termsOfService}}}{{/termsOfService}}" @@ -97,10 +97,10 @@ namespace {{packageName}} .UseSwaggerUI(c => { //TODO: Either use the SwaggerGen generated Swagger contract (generated from C# classes) - c.SwaggerEndpoint("/swagger/{{#version}}{{{version}}}{{/version}}{{^version}}v1{{/version}}/swagger.json", "{{#appName}}{{{appName}}}{{/appName}}{{^appName}}{{packageName}}{{/appName}}"); + c.SwaggerEndpoint("/swagger/{{#version}}{{{version}}}{{/version}}{{^version}}v1{{/version}}/openapi.json", "{{#appName}}{{{appName}}}{{/appName}}{{^appName}}{{packageName}}{{/appName}}"); //TODO: Or alternatively use the original Swagger contract that's included in the static files - // c.SwaggerEndpoint("/swagger-original.json", "{{#appName}}{{{appName}}}{{/appName}}{{^appName}}{{packageName}}{{/appName}} Original"); + // c.SwaggerEndpoint("/openapi-original.json", "{{#appName}}{{{appName}}}{{/appName}}{{^appName}}{{packageName}}{{/appName}} Original"); }); if (env.IsDevelopment()) diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/wwwroot/openapi-original.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/wwwroot/openapi-original.mustache new file mode 100644 index 000000000000..2c1b461cf000 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/aspnetcore/wwwroot/openapi-original.mustache @@ -0,0 +1 @@ +{{{openapi-json}}} diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/wwwroot/swagger-original.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/wwwroot/swagger-original.mustache deleted file mode 100644 index 9bf6bbcffba5..000000000000 --- a/modules/openapi-generator/src/main/resources/aspnetcore/wwwroot/swagger-original.mustache +++ /dev/null @@ -1 +0,0 @@ -{{{swagger-json}}} diff --git a/modules/openapi-generator/src/main/resources/bash/README.md b/modules/openapi-generator/src/main/resources/bash/README.md index 88fd2dfbee6c..906e237b246c 100644 --- a/modules/openapi-generator/src/main/resources/bash/README.md +++ b/modules/openapi-generator/src/main/resources/bash/README.md @@ -47,7 +47,7 @@ Define custom codegen properties in a Json file, e.g.: Generate the client: ```shell -$ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate -i http://petstore.swagger.io/v2/swagger.json -l bash -o generated/bash/petstore -c modules/swagger-codegen/src/test/resources/2_0/bash-config.json +$ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -i http://petstore.swagger.io/v2/swagger.json -l bash -o generated/bash/petstore -c modules/openapi-generator/src/test/resources/2_0/bash-config.json $ chmod +x generated/bash/petstore/petstore-cli ``` diff --git a/modules/openapi-generator/src/main/resources/codegen/README.mustache b/modules/openapi-generator/src/main/resources/codegen/README.mustache index 9fa9458a0814..3564eff83497 100644 --- a/modules/openapi-generator/src/main/resources/codegen/README.mustache +++ b/modules/openapi-generator/src/main/resources/codegen/README.mustache @@ -46,7 +46,7 @@ mvn package In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: ``` -java -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar org.openapitools.codegen.Codegen -l {{name}} -i /path/to/swagger.yaml -o ./test +java -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar org.openapitools.codegen.Codegen -l {{name}} -i /path/to/openapi.yaml -o ./test ``` Now your templates are available to the client generator and you can write output values diff --git a/modules/openapi-generator/src/main/resources/cpprest/api-source.mustache b/modules/openapi-generator/src/main/resources/cpprest/api-source.mustache index d55a7ef020fb..9ed43b62dc57 100644 --- a/modules/openapi-generator/src/main/resources/cpprest/api-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpprest/api-source.mustache @@ -125,20 +125,6 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r {{/isContainer}} {{/required}} { - {{#isContainer}} - {{#isQueryParam}} - queryParams[utility::conversions::to_string_t("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{^required}}*{{/required}}{{paramName}}); - {{/isQueryParam}} - {{#isHeaderParam}} - headerParams[utility::conversions::to_string_t("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{^required}}*{{/required}}{{paramName}}); - {{/isHeaderParam}} - {{#isFormParam}} - {{^isFile}} - formParams[ utility::conversions::to_string_t("{{baseName}}") ] = ApiClient::parameterToArrayString<{{items.datatype}}>({{^required}}*{{/required}}{{paramName}}); - {{/isFile}} - {{/isFormParam}} - {{/isContainer}} - {{^isContainer}} {{#isQueryParam}} queryParams[utility::conversions::to_string_t("{{baseName}}")] = ApiClient::parameterToString({{^required}}*{{/required}}{{paramName}}); {{/isQueryParam}} @@ -153,7 +139,6 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r formParams[ utility::conversions::to_string_t("{{baseName}}") ] = ApiClient::parameterToString({{^required}}*{{/required}}{{paramName}}); {{/isFile}} {{/isFormParam}} - {{/isContainer}} } {{/isPathParam}} {{/isBodyParam}} @@ -187,8 +172,9 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r json = web::json::value::array(jsonArray); } {{/isListContainer}} - {{^isListContainer}} - json = ModelBase::toJson({{paramName}}); + {{^isListContainer}}{{#required}}json = ModelBase::toJson({{paramName}}); + {{/required}}{{^required}}if ({{paramName}}) + json = ModelBase::toJson(*{{paramName}});{{/required}} {{/isListContainer}} {{/isPrimitiveType}} @@ -217,15 +203,11 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r {{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}} } multipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("{{paramName}}"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); - } - {{/isListContainer}} - {{^isListContainer}} - {{#isString}}multipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("{{paramName}}"), {{paramName}})); - {{/isString}} - {{^isString}} - if({{paramName}}.get()) + }{{/isListContainer}} + {{^isListContainer}}{{#isString}}multipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("{{paramName}}"), {{paramName}})); + {{/isString}}{{^isString}}if({{^required}}{{paramName}} && (*{{paramName}}){{/required}}{{#required}}{{paramName}}{{/required}}.get()) { - {{paramName}}->toMultipart(multipart, utility::conversions::to_string_t("{{paramName}}")); + {{^required}}(*{{/required}}{{paramName}}{{^required}}){{/required}}->toMultipart(multipart, utility::conversions::to_string_t("{{paramName}}")); } {{/isString}} {{/isListContainer}} @@ -345,8 +327,9 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r result[item.first] = itemObj; {{/vendorExtensions.x-codegen-response.items.isString}}{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}} } - {{/isMapContainer}}{{^isMapContainer}}{{#vendorExtensions.x-codegen-response.isPrimitiveType}}result = ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(json); - {{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.isString}}result = ModelBase::stringFromJson(json); + {{/isMapContainer}}{{^isMapContainer}}{{#vendorExtensions.x-codegen-response.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.items.datatype}}result = ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(json); + {{/vendorExtensions.x-codegen-response.items.datatype}}{{^vendorExtensions.x-codegen-response.items.datatype}}result = ModelBase::{{vendorExtensions.x-codegen-response.datatype}}FromJson(json); + {{/vendorExtensions.x-codegen-response.items.datatype}}{{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.isString}}result = ModelBase::stringFromJson(json); {{/vendorExtensions.x-codegen-response.isString}}{{^vendorExtensions.x-codegen-response.isString}}result->fromJson(json);{{/vendorExtensions.x-codegen-response.isString}}{{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{/isMapContainer}}{{/isListContainer}} }{{#vendorExtensions.x-codegen-response.isString}} else if(responseHttpContentType == utility::conversions::to_string_t("text/plain")) diff --git a/modules/openapi-generator/src/main/resources/cpprest/apiclient-header.mustache b/modules/openapi-generator/src/main/resources/cpprest/apiclient-header.mustache index 72b2c53671b8..23bc7633171e 100644 --- a/modules/openapi-generator/src/main/resources/cpprest/apiclient-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpprest/apiclient-header.mustache @@ -39,21 +39,10 @@ public: static utility::string_t parameterToString(int32_t value); static utility::string_t parameterToString(int64_t value); static utility::string_t parameterToString(float value); + static utility::string_t parameterToString(double value); static utility::string_t parameterToString(const utility::datetime &value); - template - static utility::string_t parameterToArrayString(std::vector value) - { - utility::stringstream_t ss; - - for( size_t i = 0; i < value.size(); i++) - { - if( i > 0) ss << utility::conversions::to_string_t(", "); - ss << ApiClient::parameterToString(value[i]); - } - - return ss.str(); - } + static utility::string_t parameterToString(const std::vector& value); pplx::task callApi( const utility::string_t& path, @@ -71,6 +60,20 @@ protected: std::shared_ptr m_Configuration; }; +template +utility::string_t ApiClient::parameterToString(const std::vector& value) +{ + utility::stringstream_t ss; + + for( size_t i = 0; i < value.size(); i++) + { + if( i > 0) ss << utility::conversions::to_string_t(", "); + ss << ApiClient::parameterToString(value[i]); + } + + return ss.str(); +} + {{#apiNamespaceDeclarations}} } {{/apiNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/cpprest/apiclient-source.mustache b/modules/openapi-generator/src/main/resources/cpprest/apiclient-source.mustache index fae8c4c70b3f..e5a1500c8d5a 100644 --- a/modules/openapi-generator/src/main/resources/cpprest/apiclient-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpprest/apiclient-source.mustache @@ -49,6 +49,11 @@ utility::string_t ApiClient::parameterToString(float value) return utility::conversions::to_string_t(std::to_string(value)); } +utility::string_t ApiClient::parameterToString(double value) +{ + return utility::conversions::to_string_t(std::to_string(value)); +} + utility::string_t ApiClient::parameterToString(const utility::datetime &value) { return utility::conversions::to_string_t(value.to_string(utility::datetime::ISO_8601)); diff --git a/modules/openapi-generator/src/main/resources/cpprest/modelbase-header.mustache b/modules/openapi-generator/src/main/resources/cpprest/modelbase-header.mustache index a68bc0cc2276..83271bf79d9f 100644 --- a/modules/openapi-generator/src/main/resources/cpprest/modelbase-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpprest/modelbase-header.mustache @@ -15,6 +15,8 @@ #include #include +#include + {{#modelNamespaceDeclarations}} namespace {{this}} { {{/modelNamespaceDeclarations}} @@ -41,6 +43,8 @@ public: static web::json::value toJson( int64_t value ); static web::json::value toJson( double value ); static web::json::value toJson( bool value ); + template + static web::json::value toJson(const std::vector& value); static int64_t int64_tFromJson(web::json::value& val); static int32_t int32_tFromJson(web::json::value& val); @@ -58,6 +62,8 @@ public: static std::shared_ptr toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); static std::shared_ptr toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); static std::shared_ptr toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + template + static std::shared_ptr toHttpContent( const utility::string_t& name, const std::vector& value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); static int64_t int64_tFromHttpContent(std::shared_ptr val); static int32_t int32_tFromHttpContent(std::shared_ptr val); @@ -74,6 +80,27 @@ public: static std::shared_ptr fromBase64( const utility::string_t& encoded ); }; +template +web::json::value ModelBase::toJson(const std::vector& value) { + std::vector ret; + for (auto& x : value) { + ret.push_back(toJson(x)); + } + + return web::json::value::array(ret); +} + +template +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const std::vector& value, const utility::string_t& contentType ) { + web::json::value json_array = ModelBase::toJson(value); + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(json_array.serialize()) ) ) ); + return content; +} + {{#modelNamespaceDeclarations}} } {{/modelNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/nancyfx/Project.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/Project.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/Project.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/Project.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/Solution.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/Solution.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/Solution.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/Solution.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/api.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/api.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/api.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/api.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/innerApiEnum.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/innerApiEnum.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/innerApiEnum.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/innerApiEnum.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/innerApiEnumName.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/innerApiEnumName.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/innerApiEnumName.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/innerApiEnumName.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/innerModelEnum.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/innerModelEnum.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/innerModelEnum.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/innerModelEnum.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/innerParameterType.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/innerParameterType.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/innerParameterType.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/innerParameterType.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/innerParameterValueOfArgs.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/innerParameterValueOfArgs.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/innerParameterValueOfArgs.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/innerParameterValueOfArgs.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/localDateConverter.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/localDateConverter.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/localDateConverter.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/localDateConverter.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/model.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/model.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/model.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/model.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/modelEnum.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/modelEnum.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/modelEnum.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/modelEnum.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/modelGeneric.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/modelGeneric.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/modelGeneric.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/modelMutable.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/modelMutable.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/modelMutable.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/modelMutable.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/nullableDataType.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/nullableDataType.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/nullableDataType.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/nullableDataType.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/nuspec.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/nuspec.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/nuspec.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/nuspec.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/packages.config.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/packages.config.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/packages.config.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/packages.config.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/parameters.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/parameters.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/parameters.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/parameters.mustache diff --git a/modules/openapi-generator/src/main/resources/nancyfx/paramsList.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/paramsList.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/nancyfx/paramsList.mustache rename to modules/openapi-generator/src/main/resources/csharp-nancyfx/paramsList.mustache diff --git a/modules/openapi-generator/src/main/resources/dart/api.mustache b/modules/openapi-generator/src/main/resources/dart/api.mustache index 4717508cd378..99a49364e334 100644 --- a/modules/openapi-generator/src/main/resources/dart/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart/api.mustache @@ -51,24 +51,30 @@ class {{classname}} { if(contentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = new MultipartRequest(null, null); - {{#formParams}}{{#notFile}} + {{#formParams}} + {{^isFile}} if ({{paramName}} != null) { hasFields = true; mp.fields['{{baseName}}'] = parameterToString({{paramName}}); } - {{/notFile}}{{#isFile}} + {{/isFile}} + {{#isFile}} if ({{paramName}} != null) { hasFields = true; mp.fields['{{baseName}}'] = {{paramName}}.field; mp.files.add({{paramName}}); } - {{/isFile}}{{/formParams}} + {{/isFile}} + {{/formParams}} if(hasFields) postBody = mp; } else { - {{#formParams}}{{#notFile}}if ({{paramName}} != null) - formParams['{{baseName}}'] = parameterToString({{paramName}});{{/notFile}} + {{#formParams}} + {{^isFile}} + if ({{paramName}} != null) + formParams['{{baseName}}'] = parameterToString({{paramName}}); + {{/isFile}} {{/formParams}} } diff --git a/modules/openapi-generator/src/main/resources/elixir/deserializer.ex.mustache b/modules/openapi-generator/src/main/resources/elixir/deserializer.ex.mustache index 931ba8f7b9cb..ada1cf1346dd 100644 --- a/modules/openapi-generator/src/main/resources/elixir/deserializer.ex.mustache +++ b/modules/openapi-generator/src/main/resources/elixir/deserializer.ex.mustache @@ -21,11 +21,15 @@ defmodule {{moduleName}}.Deserializer do |> Map.update!(field, &(Map.new(&1, fn {key, val} -> {key, Poison.Decode.decode(val, Keyword.merge(options, [as: struct(mod)]))} end))) end def deserialize(model, field, :date, _, _options) do - case DateTime.from_iso8601(Map.get(model, field)) do - {:ok, datetime} -> - Map.put(model, field, datetime) - _ -> - model + value = Map.get(model, field) + case is_binary(value) do + true -> case DateTime.from_iso8601(value) do + {:ok, datetime, _offset} -> + Map.put(model, field, datetime) + _ -> + model + end + false -> model end end end diff --git a/modules/openapi-generator/src/main/resources/erlang-server/router.mustache b/modules/openapi-generator/src/main/resources/erlang-server/router.mustache index b5b7bd9f52e9..b6b393a1e476 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/router.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/router.mustache @@ -69,6 +69,6 @@ prepare_validator() -> get_swagger_path() -> {ok, AppName} = application:get_application(?MODULE), - filename:join({{packageName}}_utils:priv_dir(AppName), "swagger.json"). + filename:join({{packageName}}_utils:priv_dir(AppName), "openapi.json"). diff --git a/modules/openapi-generator/src/main/resources/erlang-server/swagger.mustache b/modules/openapi-generator/src/main/resources/erlang-server/swagger.mustache index 9bf6bbcffba5..2c1b461cf000 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/swagger.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/swagger.mustache @@ -1 +1 @@ -{{{swagger-json}}} +{{{openapi-json}}} diff --git a/modules/openapi-generator/src/main/resources/flaskConnexion/README.mustache b/modules/openapi-generator/src/main/resources/flaskConnexion/README.mustache index b73b9e311b07..acaad3fac30d 100644 --- a/modules/openapi-generator/src/main/resources/flaskConnexion/README.mustache +++ b/modules/openapi-generator/src/main/resources/flaskConnexion/README.mustache @@ -38,7 +38,7 @@ http://localhost:{{serverPort}}{{contextPath}}/ui/ Your Swagger definition lives here: ``` -http://localhost:{{serverPort}}{{contextPath}}/swagger.json +http://localhost:{{serverPort}}{{contextPath}}/openapi.json ``` To launch the integration tests, use tox: diff --git a/modules/openapi-generator/src/main/resources/flaskConnexion/__init__test.mustache b/modules/openapi-generator/src/main/resources/flaskConnexion/__init__test.mustache index 9cea80bc6302..be8ae2c1881b 100644 --- a/modules/openapi-generator/src/main/resources/flaskConnexion/__init__test.mustache +++ b/modules/openapi-generator/src/main/resources/flaskConnexion/__init__test.mustache @@ -10,7 +10,7 @@ class BaseTestCase(TestCase): def create_app(self): logging.getLogger('connexion.operation').setLevel('ERROR') - app = connexion.App(__name__, specification_dir='../swagger/') + app = connexion.App(__name__, specification_dir='../openapi/') app.app.json_encoder = JSONEncoder - app.add_api('swagger.yaml') + app.add_api('openapi.yaml') return app.app diff --git a/modules/openapi-generator/src/main/resources/flaskConnexion/__main__.mustache b/modules/openapi-generator/src/main/resources/flaskConnexion/__main__.mustache index 10756347223c..fa76ee4de80c 100644 --- a/modules/openapi-generator/src/main/resources/flaskConnexion/__main__.mustache +++ b/modules/openapi-generator/src/main/resources/flaskConnexion/__main__.mustache @@ -11,9 +11,9 @@ from {{packageName}} import encoder def main(): - app = connexion.App(__name__, specification_dir='./swagger/') + app = connexion.App(__name__, specification_dir='./openapi/') app.app.json_encoder = encoder.JSONEncoder - app.add_api('swagger.yaml', arguments={'title': '{{appName}}'}) + app.add_api('openapi.yaml', arguments={'title': '{{appName}}'}) app.run(port={{serverPort}}) diff --git a/modules/openapi-generator/src/main/resources/flaskConnexion/openapi.mustache b/modules/openapi-generator/src/main/resources/flaskConnexion/openapi.mustache new file mode 100644 index 000000000000..51ebafb0187d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/flaskConnexion/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/flaskConnexion/setup.mustache b/modules/openapi-generator/src/main/resources/flaskConnexion/setup.mustache index 56f8bc1ec176..57a047e7bb0b 100644 --- a/modules/openapi-generator/src/main/resources/flaskConnexion/setup.mustache +++ b/modules/openapi-generator/src/main/resources/flaskConnexion/setup.mustache @@ -21,10 +21,10 @@ setup( description="{{appName}}", author_email="{{infoEmail}}", url="{{packageUrl}}", - keywords=["Swagger", "{{appName}}"], + keywords=["OpenAPI", "{{appName}}"], install_requires=REQUIRES, packages=find_packages(), - package_data={'': ['swagger/swagger.yaml']}, + package_data={'': ['openapi/openapi.yaml']}, include_package_data=True, entry_points={ 'console_scripts': ['{{packageName}}={{packageName}}.__main__:main']}, diff --git a/modules/openapi-generator/src/main/resources/flaskConnexion/swagger.mustache b/modules/openapi-generator/src/main/resources/flaskConnexion/swagger.mustache deleted file mode 100644 index 51560926bba1..000000000000 --- a/modules/openapi-generator/src/main/resources/flaskConnexion/swagger.mustache +++ /dev/null @@ -1 +0,0 @@ -{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/go-server/swagger.mustache b/modules/openapi-generator/src/main/resources/go-server/swagger.mustache index 51560926bba1..51ebafb0187d 100644 --- a/modules/openapi-generator/src/main/resources/go-server/swagger.mustache +++ b/modules/openapi-generator/src/main/resources/go-server/swagger.mustache @@ -1 +1 @@ -{{{swagger-yaml}}} \ No newline at end of file +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/go/swagger.mustache b/modules/openapi-generator/src/main/resources/go/swagger.mustache index 51560926bba1..51ebafb0187d 100644 --- a/modules/openapi-generator/src/main/resources/go/swagger.mustache +++ b/modules/openapi-generator/src/main/resources/go/swagger.mustache @@ -1 +1 @@ -{{{swagger-yaml}}} \ No newline at end of file +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/haskell-http-client/haskell-http-client.cabal.mustache b/modules/openapi-generator/src/main/resources/haskell-http-client/haskell-http-client.cabal.mustache index 3cda661d0609..a947b7f0f3c0 100644 --- a/modules/openapi-generator/src/main/resources/haskell-http-client/haskell-http-client.cabal.mustache +++ b/modules/openapi-generator/src/main/resources/haskell-http-client/haskell-http-client.cabal.mustache @@ -29,7 +29,7 @@ cabal-version: >= 1.10 extra-source-files: README.md - swagger.yaml + openapi.yaml library hs-source-dirs: diff --git a/modules/openapi-generator/src/main/resources/haskell-http-client/openapi.mustache b/modules/openapi-generator/src/main/resources/haskell-http-client/openapi.mustache new file mode 100644 index 000000000000..51ebafb0187d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/haskell-http-client/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/haskell-http-client/swagger.mustache b/modules/openapi-generator/src/main/resources/haskell-http-client/swagger.mustache deleted file mode 100644 index 51560926bba1..000000000000 --- a/modules/openapi-generator/src/main/resources/haskell-http-client/swagger.mustache +++ /dev/null @@ -1 +0,0 @@ -{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-pkmst/formParams.mustache b/modules/openapi-generator/src/main/resources/java-pkmst/formParams.mustache index 8f6cb5213c48..62ac260ef49a 100644 --- a/modules/openapi-generator/src/main/resources/java-pkmst/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/java-pkmst/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{baseName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{baseName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}@ApiParam(value = "file detail") {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-pkmst/readme.mustache b/modules/openapi-generator/src/main/resources/java-pkmst/readme.mustache index 38701b4e848e..3b0ea216f7c1 100644 --- a/modules/openapi-generator/src/main/resources/java-pkmst/readme.mustache +++ b/modules/openapi-generator/src/main/resources/java-pkmst/readme.mustache @@ -50,7 +50,7 @@ will be enabled. inside the swagger codegen maven plugin under the configuration section - product-swagger.yaml + product-openapi.yaml pkmst ${project.build.directory}/generated-sources diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache index e64785e01b15..66cc4ac838ee 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache @@ -1,3 +1,6 @@ +{{#hasEnums}} +import com.squareup.moshi.Json +{{/hasEnums}} /** * {{{description}}} {{#vars}} @@ -18,7 +21,7 @@ data class {{classname}} ( */ enum class {{nameInCamelCase}}(val value: {{datatype}}){ {{#allowableValues}}{{#enumVars}} - {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + @Json(name = {{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/enumVars}}{{/allowableValues}} } {{/isEnum}}{{/vars}}{{/hasEnums}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache index 791398b97894..6b85b0fba537 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache @@ -1,9 +1,11 @@ +import com.squareup.moshi.Json + /** * {{{description}}} * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ enum class {{classname}}(val value: {{dataType}}){ {{#allowableValues}}{{#enumVars}} - {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + @Json(name = {{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/enumVars}}{{/allowableValues}} } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/ApiClient.kt.mustache index e46256a35673..934cf63524d0 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/ApiClient.kt.mustache @@ -12,7 +12,12 @@ open class ApiClient(val baseUrl: String) { protected val XmlMediaType = "application/xml" @JvmStatic - val client : OkHttpClient = OkHttpClient() + val client by lazy { + builder.build() + } + + @JvmStatic + val builder: OkHttpClient.Builder = OkHttpClient.Builder() @JvmStatic var defaultHeaders: Map by ApplicationDelegates.setOnce(mapOf(ContentType to JsonMediaType, Accept to JsonMediaType)) diff --git a/modules/openapi-generator/src/main/resources/nodejs/index-gcf.mustache b/modules/openapi-generator/src/main/resources/nodejs/index-gcf.mustache index b406ff7f1404..6cf3a5a5c1c1 100644 --- a/modules/openapi-generator/src/main/resources/nodejs/index-gcf.mustache +++ b/modules/openapi-generator/src/main/resources/nodejs/index-gcf.mustache @@ -11,7 +11,7 @@ var options = { }; // The Swagger document (require it, build it programmatically, fetch it from a URL, ...) -var spec = fs.readFileSync('./api/swagger.yaml', 'utf8'); +var spec = fs.readFileSync('./api/openapi.yaml', 'utf8'); var swaggerDoc = jsyaml.safeLoad(spec); function toPromise(f, req, res) { diff --git a/modules/openapi-generator/src/main/resources/nodejs/index.mustache b/modules/openapi-generator/src/main/resources/nodejs/index.mustache index a462b154e1dd..b0054f883c2f 100644 --- a/modules/openapi-generator/src/main/resources/nodejs/index.mustache +++ b/modules/openapi-generator/src/main/resources/nodejs/index.mustache @@ -11,13 +11,13 @@ var serverPort = {{serverPort}}; // swaggerRouter configuration var options = { - swaggerUi: path.join(__dirname, '/swagger.json'), + swaggerUi: path.join(__dirname, '/openapi.json'), controllers: path.join(__dirname, './controllers'), useStubs: process.env.NODE_ENV === 'development' // Conditionally turn on stubs (mock mode) }; // The Swagger document (require it, build it programmatically, fetch it from a URL, ...) -var spec = fs.readFileSync(path.join(__dirname,'api/swagger.yaml'), 'utf8'); +var spec = fs.readFileSync(path.join(__dirname,'api/openapi.yaml'), 'utf8'); var swaggerDoc = jsyaml.safeLoad(spec); // Initialize the Swagger middleware diff --git a/modules/openapi-generator/src/main/resources/nodejs/openapi.mustache b/modules/openapi-generator/src/main/resources/nodejs/openapi.mustache new file mode 100644 index 000000000000..51ebafb0187d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/nodejs/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/nodejs/swagger.mustache b/modules/openapi-generator/src/main/resources/nodejs/swagger.mustache deleted file mode 100644 index 51560926bba1..000000000000 --- a/modules/openapi-generator/src/main/resources/nodejs/swagger.mustache +++ /dev/null @@ -1 +0,0 @@ -{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/objc/api-body.mustache b/modules/openapi-generator/src/main/resources/objc/api-body.mustache index f083aed1cd72..ee605dade065 100644 --- a/modules/openapi-generator/src/main/resources/objc/api-body.mustache +++ b/modules/openapi-generator/src/main/resources/objc/api-body.mustache @@ -132,11 +132,11 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; {{/bodyParam}} {{^bodyParam}} {{#formParams}} - {{#notFile}} + {{^isFile}} if ({{paramName}}) { formParams[@"{{baseName}}"] = {{paramName}}; } - {{/notFile}} + {{/isFile}} {{#isFile}} localVarFiles[@"{{paramName}}"] = {{paramName}}; {{/isFile}} diff --git a/modules/openapi-generator/src/main/resources/openapi-yaml/README.md b/modules/openapi-generator/src/main/resources/openapi-yaml/README.md new file mode 100644 index 000000000000..6b0f68482016 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/openapi-yaml/README.md @@ -0,0 +1,2 @@ +# OpenAPI YAML +This is a OpenAPI YAML built by the [openapi-generator](https://github.com/openapitools/openapi-genreator) project. \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/openapi-yaml/openapi.mustache b/modules/openapi-generator/src/main/resources/openapi-yaml/openapi.mustache new file mode 100644 index 000000000000..51ebafb0187d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/openapi-yaml/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/openapi/README.md b/modules/openapi-generator/src/main/resources/openapi/README.md new file mode 100644 index 000000000000..6c6352fdaef6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/openapi/README.md @@ -0,0 +1,2 @@ +# OpenAPI JSON +This is a OpenAPI JSON built by the [openapi-generator](https://github.com/openapitools/openapi-genreator) project. \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php/model_generic.mustache b/modules/openapi-generator/src/main/resources/php/model_generic.mustache index ec90e6e3ab1e..9daf49f13799 100644 --- a/modules/openapi-generator/src/main/resources/php/model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/php/model_generic.mustache @@ -1,6 +1,6 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}{{^parentSchema}}implements ModelInterface, ArrayAccess{{/parentSchema}} { - const DISCRIMINATOR = {{#discriminator}}'{{discriminator}}'{{/discriminator}}{{^discriminator}}null{{/discriminator}}; + const DISCRIMINATOR = {{#discriminator}}'{{discriminatorName}}'{{/discriminator}}{{^discriminator}}null{{/discriminator}}; /** * The original name of the model. @@ -166,7 +166,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}{{^pa {{#discriminator}} // Initialize discriminator property with the model name. - $discriminator = array_search('{{discriminator}}', self::$attributeMap); + $discriminator = array_search('{{discriminatorName}}', self::$attributeMap); $this->container[$discriminator] = static::$swaggerModelName; {{/discriminator}} } @@ -194,7 +194,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}{{^pa {{#isEnum}} {{^isContainer}} $allowedValues = $this->{{getter}}AllowableValues(); - if (!is_null($this->container['{{name}}']) && !in_array($this->container['{{name}}'], $allowedValues)) { + if (!is_null($this->container['{{name}}']) && !in_array($this->container['{{name}}'], $allowedValues, true)) { $invalidProperties[] = sprintf( "invalid value for '{{name}}', must be one of '%s'", implode("', '", $allowedValues) @@ -205,13 +205,13 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}{{^pa {{/isEnum}} {{#hasValidation}} {{#maxLength}} - if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}(strlen($this->container['{{name}}']) > {{maxLength}})) { + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}(mb_strlen($this->container['{{name}}']) > {{maxLength}})) { $invalidProperties[] = "invalid value for '{{name}}', the character length must be smaller than or equal to {{{maxLength}}}."; } {{/maxLength}} {{#minLength}} - if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}(strlen($this->container['{{name}}']) < {{minLength}})) { + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}(mb_strlen($this->container['{{name}}']) < {{minLength}})) { $invalidProperties[] = "invalid value for '{{name}}', the character length must be bigger than or equal to {{{minLength}}}."; } @@ -274,19 +274,19 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}{{^pa {{#isEnum}} {{^isContainer}} $allowedValues = $this->{{getter}}AllowableValues(); - if (!is_null($this->container['{{name}}']) && !in_array($this->container['{{name}}'], $allowedValues)) { + if (!is_null($this->container['{{name}}']) && !in_array($this->container['{{name}}'], $allowedValues, true)) { return false; } {{/isContainer}} {{/isEnum}} {{#hasValidation}} {{#maxLength}} - if (strlen($this->container['{{name}}']) > {{maxLength}}) { + if (mb_strlen($this->container['{{name}}']) > {{maxLength}}) { return false; } {{/maxLength}} {{#minLength}} - if (strlen($this->container['{{name}}']) < {{minLength}}) { + if (mb_strlen($this->container['{{name}}']) < {{minLength}}) { return false; } {{/minLength}} @@ -344,7 +344,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}{{^pa {{#isEnum}} $allowedValues = $this->{{getter}}AllowableValues(); {{^isContainer}} - if ({{^required}}!is_null(${{name}}) && {{/required}}!in_array(${{{name}}}, $allowedValues)) { + if ({{^required}}!is_null(${{name}}) && {{/required}}!in_array(${{{name}}}, $allowedValues, true)) { throw new \InvalidArgumentException( sprintf( "Invalid value for '{{name}}', must be one of '%s'", @@ -366,11 +366,11 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}{{^pa {{/isEnum}} {{#hasValidation}} {{#maxLength}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(strlen(${{name}}) > {{maxLength}})) { + if ({{^required}}!is_null(${{name}}) && {{/required}}(mb_strlen(${{name}}) > {{maxLength}})) { throw new \InvalidArgumentException('invalid length for ${{name}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.'); }{{/maxLength}} {{#minLength}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(strlen(${{name}}) < {{minLength}})) { + if ({{^required}}!is_null(${{name}}) && {{/required}}(mb_strlen(${{name}}) < {{minLength}})) { throw new \InvalidArgumentException('invalid length for ${{name}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.'); } {{/minLength}} diff --git a/modules/openapi-generator/src/main/resources/pistache-server/api-source.mustache b/modules/openapi-generator/src/main/resources/pistache-server/api-source.mustache index cfae1635b0a6..2545aca76aa8 100644 --- a/modules/openapi-generator/src/main/resources/pistache-server/api-source.mustache +++ b/modules/openapi-generator/src/main/resources/pistache-server/api-source.mustache @@ -75,7 +75,8 @@ void {{classname}}::{{operationIdSnakeCase}}_handler(const Pistache::Rest::Reque {{#bodyParam}} nlohmann::json request_body = nlohmann::json::parse(request.body()); {{^isPrimitiveType}} - {{paramName}}.fromJson(request_body); {{/isPrimitiveType}} + {{paramName}}.fromJson(request_body); + {{/isPrimitiveType}} {{#isPrimitiveType}} // The conversion is done automatically by the json library {{paramName}} = request_body; diff --git a/modules/openapi-generator/src/main/resources/python/api.mustache b/modules/openapi-generator/src/main/resources/python/api.mustache index a65946f578dc..512d2570b122 100644 --- a/modules/openapi-generator/src/main/resources/python/api.mustache +++ b/modules/openapi-generator/src/main/resources/python/api.mustache @@ -171,7 +171,7 @@ class {{classname}}(object): local_var_files = {} {{#formParams}} if '{{paramName}}' in params: - {{#notFile}}form_params.append(('{{baseName}}', params['{{paramName}}'])){{/notFile}}{{#isFile}}local_var_files['{{baseName}}'] = params['{{paramName}}']{{/isFile}}{{#isListContainer}} # noqa: E501 + {{^isFile}}form_params.append(('{{baseName}}', params['{{paramName}}'])){{/isFile}}{{#isFile}}local_var_files['{{baseName}}'] = params['{{paramName}}']{{/isFile}}{{#isListContainer}} # noqa: E501 collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} # noqa: E501 {{/formParams}} diff --git a/modules/openapi-generator/src/main/resources/qt5cpp/Project.mustache b/modules/openapi-generator/src/main/resources/qt5cpp/Project.mustache new file mode 100644 index 000000000000..dac7276b98cd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/qt5cpp/Project.mustache @@ -0,0 +1,43 @@ +QT += network + +HEADERS += \ +# Models +{{#models}} +{{#model}} + $${PWD}/{{classname}}.h \ +{{/model}} +{{/models}} +# APIs +{{#apiInfo}} +{{#apis}} +{{#operations}} + $${PWD}/{{classname}}.h \ +{{/operations}} +{{/apis}} +{{/apiInfo}} +# Others + $${PWD}/{{prefix}}Helpers.h \ + $${PWD}/{{prefix}}HttpRequest.h \ + $${PWD}/{{prefix}}ModelFactory.h \ + $${PWD}/{{prefix}}Object.h \ + $${PWD}/{{prefix}}QObjectWrapper.h + +SOURCES += \ +# Models +{{#models}} +{{#model}} + $${PWD}/{{classname}}.cpp \ +{{/model}} +{{/models}} +# APIs +{{#apiInfo}} +{{#apis}} +{{#operations}} + $${PWD}/{{classname}}.cpp \ +{{/operations}} +{{/apis}} +{{/apiInfo}} +# Others + $${PWD}/{{prefix}}Helpers.cpp \ + $${PWD}/{{prefix}}HttpRequest.cpp + diff --git a/modules/openapi-generator/src/main/resources/qt5cpp/QObjectWrapper.h.mustache b/modules/openapi-generator/src/main/resources/qt5cpp/QObjectWrapper.h.mustache new file mode 100644 index 000000000000..efd71407777b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/qt5cpp/QObjectWrapper.h.mustache @@ -0,0 +1,28 @@ +{{>licenseInfo}} +#ifndef {{prefix}}_QOBJECT_WRAPPER_H +#define {{prefix}}_QOBJECT_WRAPPER_H + +#include + +{{#cppNamespaceDeclarations}} +namespace {{this}} { +{{/cppNamespaceDeclarations}} + + template + class {{prefix}}QObjectWrapper : public QObject { + public: + {{prefix}}QObjectWrapper(ObjectPtrT ptr){ + data = ptr; + } + ~{{prefix}}QObjectWrapper(){ + delete data; + } + private : + ObjectPtrT data; + }; + +{{#cppNamespaceDeclarations}} +} +{{/cppNamespaceDeclarations}} + +#endif // {{prefix}}_QOBJECT_WRAPPER_H \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/qt5cpp/api-body.mustache b/modules/openapi-generator/src/main/resources/qt5cpp/api-body.mustache index 80edd8b10240..52891ab59513 100644 --- a/modules/openapi-generator/src/main/resources/qt5cpp/api-body.mustache +++ b/modules/openapi-generator/src/main/resources/qt5cpp/api-body.mustache @@ -2,6 +2,7 @@ #include "{{classname}}.h" #include "{{prefix}}Helpers.h" #include "{{prefix}}ModelFactory.h" +#include "{{prefix}}QObjectWrapper.h" #include #include @@ -150,20 +151,30 @@ void QByteArray array (json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonArray jsonArray = doc.array(); - + auto wrapper = new {{prefix}}QObjectWrapper<{{{returnType}}}> (output); + wrapper->deleteLater(); foreach(QJsonValue obj, jsonArray) { {{{returnBaseType}}}* o = new {{returnBaseType}}(); QJsonObject jv = obj.toObject(); QJsonObject * ptr = (QJsonObject*)&jv; o->fromJsonObject(*ptr); + auto objwrapper = new {{prefix}}QObjectWrapper<{{{returnBaseType}}}*> (o); + objwrapper->deleteLater(); output->append(o); } {{/isListContainer}} - {{^isListContainer}} {{^isMapContainer}} {{#returnTypeIsPrimitive}} {{{returnType}}} output; // TODO add primitive output support + {{#isByteArray}}auto wrapper = new {{prefix}}QObjectWrapper<{{{returnType}}}> (output); + wrapper->deleteLater();{{/isByteArray}} + {{#isDateTime}}auto wrapper = new {{prefix}}QObjectWrapper<{{{returnType}}}> (output); + wrapper->deleteLater();{{/isDateTime}} + {{#isDate}}auto wrapper = new {{prefix}}QObjectWrapper<{{{returnType}}}> (output); + wrapper->deleteLater();{{/isDate}} + {{#isString}}auto wrapper = new {{prefix}}QObjectWrapper<{{{returnType}}}> (output); + wrapper->deleteLater();{{/isString}} {{/returnTypeIsPrimitive}} {{/isMapContainer}} {{#isMapContainer}} @@ -174,15 +185,17 @@ void QJsonObject obj = doc.object(); foreach(QString key, obj.keys()) { - qint32* val; + {{returnBaseType}} val; setValue(&val, obj[key], "{{returnBaseType}}", QString()); - output->insert(key, *val); + output->insert(key, val); } {{/isMapContainer}} {{^isMapContainer}} {{^returnTypeIsPrimitive}} QString json(worker->response); {{{returnType}}} output = static_cast<{{{returnType}}}>(create(json, QString("{{{returnBaseType}}}"))); + auto wrapper = new {{prefix}}QObjectWrapper<{{{returnType}}}> (output); + wrapper->deleteLater(); {{/returnTypeIsPrimitive}} {{/isMapContainer}} {{/isListContainer}} diff --git a/modules/openapi-generator/src/main/resources/qt5cpp/model-body.mustache b/modules/openapi-generator/src/main/resources/qt5cpp/model-body.mustache index d903823911a6..7634ec32ed7f 100644 --- a/modules/openapi-generator/src/main/resources/qt5cpp/model-body.mustache +++ b/modules/openapi-generator/src/main/resources/qt5cpp/model-body.mustache @@ -220,7 +220,24 @@ bool bool isObjectUpdated = false; do{ {{#vars}} - {{#isPrimitiveType}}if(m_{{name}}_isSet){ isObjectUpdated = true; break;}{{/isPrimitiveType}}{{#isContainer}}if({{name}}->size() > 0){ isObjectUpdated = true; break;}{{/isContainer}}{{^isContainer}}{{#complexType}}{{^isString}}{{^isDateTime}}if({{name}} != nullptr && {{name}}->isSet()){ isObjectUpdated = true; break;}{{/isDateTime}}{{/isString}}{{#isString}}if({{name}} != nullptr && *{{name}} != QString("")){ isObjectUpdated = true; break;}{{/isString}}{{/complexType}}{{/isContainer}} + {{#isPrimitiveType}} + if(m_{{name}}_isSet){ isObjectUpdated = true; break;} + {{/isPrimitiveType}} + {{#isContainer}} + if({{name}}->size() > 0){ isObjectUpdated = true; break;} + {{/isContainer}} + {{^isContainer}} + {{#complexType}} + {{^isString}} + {{^isDateTime}} + if({{name}} != nullptr && {{name}}->isSet()){ isObjectUpdated = true; break;} + {{/isDateTime}} + {{/isString}} + {{#isString}} + if({{name}} != nullptr && *{{name}} != QString("")){ isObjectUpdated = true; break;} + {{/isString}} + {{/complexType}} + {{/isContainer}} {{/vars}} }while(false); return isObjectUpdated; diff --git a/modules/openapi-generator/src/main/resources/restbed/api-source.mustache b/modules/openapi-generator/src/main/resources/restbed/api-source.mustache index ab9ab30ddaa7..35196da731de 100644 --- a/modules/openapi-generator/src/main/resources/restbed/api-source.mustache +++ b/modules/openapi-generator/src/main/resources/restbed/api-source.mustache @@ -75,7 +75,7 @@ void {{classname}}{{vendorExtensions.x-codegen-resourceName}}Resource::{{httpMet // Getting the path params {{#pathParams}} {{#isPrimitiveType}} - const {{dataType}} {{paramName}} = request->get_path_parameter("{{paramName}}", {{#isString}}""{{/isString}}{{#isInteger}}0{{/isInteger}}{{#isLong}}0L{{/isLong}}{{#isFloat}}0.0f{{/isFloat}}{{#isDouble}}0.0{{/isDouble}}); + const {{{dataType}}} {{{paramName}}} = request->get_path_parameter("{{paramName}}", {{#isString}}""{{/isString}}{{#isInteger}}0{{/isInteger}}{{#isLong}}0L{{/isLong}}{{#isFloat}}0.0f{{/isFloat}}{{#isDouble}}0.0{{/isDouble}}); {{/isPrimitiveType}} {{/pathParams}} {{/hasPathParams}} @@ -84,7 +84,7 @@ void {{classname}}{{vendorExtensions.x-codegen-resourceName}}Resource::{{httpMet // Getting the query params {{#queryParams}} {{#isPrimitiveType}} - const {{dataType}} {{paramName}} = request->get_query_parameter("{{paramName}}", {{#isString}}""{{/isString}}{{#isInteger}}0{{/isInteger}}{{#isLong}}0L{{/isLong}}{{#isFloat}}0.0f{{/isFloat}}{{#isDouble}}0.0{{/isDouble}}); + const {{{dataType}}} {{{paramName}}} = request->get_query_parameter("{{paramName}}", {{#isString}}""{{/isString}}{{#isInteger}}0{{/isInteger}}{{#isLong}}0L{{/isLong}}{{#isFloat}}0.0f{{/isFloat}}{{#isDouble}}0.0{{/isDouble}}); {{/isPrimitiveType}} {{/queryParams}} {{/hasQueryParams}} @@ -93,7 +93,7 @@ void {{classname}}{{vendorExtensions.x-codegen-resourceName}}Resource::{{httpMet // Getting the headers {{#headerParams}} {{#isPrimitiveType}} - const {{dataType}} {{paramName}} = request->get_header("{{paramName}}", {{#isString}}""{{/isString}}{{#isInteger}}0{{/isInteger}}{{#isLong}}0L{{/isLong}}{{#isFloat}}0.0f{{/isFloat}}{{#isDouble}}0.0{{/isDouble}}); + const {{{dataType}}} {{{paramName}}} = request->get_header("{{paramName}}", {{#isString}}""{{/isString}}{{#isInteger}}0{{/isInteger}}{{#isLong}}0L{{/isLong}}{{#isFloat}}0.0f{{/isFloat}}{{#isDouble}}0.0{{/isDouble}}); {{/isPrimitiveType}} {{/headerParams}} {{/hasHeaderParams}} diff --git a/modules/openapi-generator/src/main/resources/ruby/README.mustache b/modules/openapi-generator/src/main/resources/ruby/README.mustache index abf26eeceda0..906035c78997 100644 --- a/modules/openapi-generator/src/main/resources/ruby/README.mustache +++ b/modules/openapi-generator/src/main/resources/ruby/README.mustache @@ -76,13 +76,19 @@ require '{{{gemName}}}' {{/authMethods}}end {{/hasAuthMethods}} -api_instance = {{{moduleName}}}::{{{classname}}}.new{{#hasParams}} -{{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} +api_instance = {{{moduleName}}}::{{{classname}}}.new +{{#requiredParams}} {{{paramName}}} = {{{example}}} # {{{dataType}}} | {{{description}}} -{{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} -opts = { {{#allParams}}{{^required}} - {{{paramName}}}: {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} # {{{dataType}}} | {{{description}}}{{/required}}{{/allParams}} -}{{/hasOptionalParams}}{{/hasParams}} +{{/requiredParams}} +{{#optionalParams}} +{{#-first}} +opts = { +{{/-first}} + {{{paramName}}}: {{{example}}}{{^-last}},{{/-last}} # {{{dataType}}} | {{{description}}} +{{#-last}} +} +{{/-last}} +{{/optionalParams}} begin {{#summary}} #{{{.}}} diff --git a/modules/openapi-generator/src/main/resources/ruby/api_doc.mustache b/modules/openapi-generator/src/main/resources/ruby/api_doc.mustache index 02fd5f7f5474..5f6f5bb5a5a9 100644 --- a/modules/openapi-generator/src/main/resources/ruby/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/ruby/api_doc.mustache @@ -11,7 +11,7 @@ Method | HTTP request | Description {{#operations}} {{#operation}} # **{{operationId}}** -> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}{{#hasParams}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}){{/hasParams}} +> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}{{#hasParams}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}){{/hasParams}} {{{summary}}}{{#notes}} @@ -36,17 +36,23 @@ require '{{{gemName}}}' {{/authMethods}}end {{/hasAuthMethods}} -api_instance = {{{moduleName}}}::{{{classname}}}.new{{#hasParams}} -{{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} +api_instance = {{{moduleName}}}::{{{classname}}}.new +{{#requiredParams}} {{{paramName}}} = {{{example}}} # {{{dataType}}} | {{{description}}} -{{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} -opts = { {{#allParams}}{{^required}} - {{{paramName}}}: {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} # {{{dataType}}} | {{{description}}}{{/required}}{{/allParams}} -}{{/hasOptionalParams}}{{/hasParams}} +{{/requiredParams}} +{{#optionalParams}} +{{#-first}} +opts = { +{{/-first}} + {{{paramName}}}: {{{example}}}{{^-last}},{{/-last}} # {{{dataType}}} | {{{description}}} +{{#-last}} +} +{{/-last}} +{{/optionalParams}} begin {{#summary}} #{{{.}}} -{{/summary}} {{#returnType}}result = {{/returnType}}api_instance.{{{operationId}}}{{#hasParams}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}){{/hasParams}}{{#returnType}} +{{/summary}} {{#returnType}}result = {{/returnType}}api_instance.{{{operationId}}}{{#hasParams}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}){{/hasParams}}{{#returnType}} p result{{/returnType}} rescue {{{moduleName}}}::ApiError => e puts "Exception when calling {{classname}}->{{{operationId}}}: #{e}" diff --git a/modules/openapi-generator/src/main/resources/rust-server/Cargo.mustache b/modules/openapi-generator/src/main/resources/rust-server/Cargo.mustache index 9e5b566b787c..787d5c72ce8c 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/Cargo.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/Cargo.mustache @@ -9,32 +9,37 @@ license = "Unlicense" [features] default = ["client", "server"] -client = ["serde_json", {{#usesXml}}"serde-xml-rs", {{/usesXml}}"serde_ignored", "hyper", "hyper-openssl", "uuid"{{#apiHasFile}}, "multipart"{{/apiHasFile}}] -server = ["serde_json", {{#usesXml}}"serde-xml-rs", {{/usesXml}}"serde_ignored", "hyper", "iron", "router", "bodyparser", "urlencoded", "uuid"{{#apiHasFile}}, "multipart"{{/apiHasFile}}] +client = ["serde_json", {{#usesUrlEncodedForm}}"serde_urlencoded", {{/usesUrlEncodedForm}} {{#usesXml}}"serde-xml-rs", {{/usesXml}}"serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "url", "uuid"{{#apiHasFile}}, "multipart"{{/apiHasFile}}] +server = ["serde_json", {{#usesXml}}"serde-xml-rs", {{/usesXml}}"serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "tokio-proto", "tokio-tls", "regex", "percent-encoding", "url", "uuid"{{#apiHasFile}}, "multipart"{{/apiHasFile}}] [dependencies] # Required by example server. # chrono = { version = "0.4", features = ["serde"] } futures = "0.1" -hyper = {version = "0.10", optional = true} -hyper-openssl = {version = "0.2", optional = true } -iron = {version = "0.5", optional = true} -swagger = "0.7" +hyper = {version = "0.11", optional = true} +hyper-tls = {version = "0.1.2", optional = true} +swagger = "0.10.0" # Not required by example server. # -bodyparser = {version = "0.7", optional = true} -url = "1.5" lazy_static = "0.2" log = "0.3.0" -multipart = {version = "0.13", optional = true} -router = {version = "0.5", optional = true} +mime = "0.3.3" +multipart = {version = "0.13.3", optional = true} +native-tls = {version = "0.1.4", optional = true} +openssl = {version = "0.9.14", optional = true} +percent-encoding = {version = "1.0.0", optional = true} +regex = {version = "0.2", optional = true} serde = "1.0" serde_derive = "1.0" serde_ignored = {version = "0.0.4", optional = true} serde_json = {version = "1.0", optional = true} -urlencoded = {version = "0.5", optional = true} +serde_urlencoded = {version = "0.5.1", optional = true} +tokio-core = {version = "0.1.6", optional = true} +tokio-proto = {version = "0.1.1", optional = true} +tokio-tls = {version = "0.1.3", optional = true, features = ["tokio-proto"]} +url = {version = "1.5", optional = true} uuid = {version = "0.5", optional = true, features = ["serde", "v4"]} # ToDo: this should be updated to point at the official crate once # https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache new file mode 100644 index 000000000000..9ed53c0b8074 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache @@ -0,0 +1,437 @@ +#![allow(unused_extern_crates)] +extern crate tokio_core; +extern crate native_tls; +extern crate hyper_tls; +extern crate openssl; +extern crate mime; +extern crate chrono; +extern crate url; +{{#apiHasFile}}extern crate multipart;{{/apiHasFile}} +{{#usesUrlEncodedForm}}extern crate serde_urlencoded;{{/usesUrlEncodedForm}} + +{{#apiUsesUuid}}use uuid;{{/apiUsesUuid}} +{{#apiHasFile}}use self::multipart::client::lazy::Multipart;{{/apiHasFile}} +use hyper; +use hyper::header::{Headers, ContentType}; +use hyper::Uri; +use self::url::percent_encoding::{utf8_percent_encode, PATH_SEGMENT_ENCODE_SET, QUERY_ENCODE_SET}; +use futures; +use futures::{Future, Stream}; +use futures::{future, stream}; +use self::tokio_core::reactor::Handle; +use std::borrow::Cow; +use std::io::{Read, Error, ErrorKind}; +use std::error; +use std::fmt; +use std::path::Path; +use std::sync::Arc; +use std::str; +use std::str::FromStr; + +use mimetypes; + +use serde_json; +{{#usesXml}}use serde_xml_rs;{{/usesXml}} + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; + +use swagger::{Context, ApiError, XSpanId}; + +use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, + {{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + }; +use models; + +/// Convert input into a base path, e.g. "http://example:123". Also checks the scheme as it goes. +fn into_base_path(input: &str, correct_scheme: Option<&'static str>) -> Result { + // First convert to Uri, since a base path is a subset of Uri. + let uri = Uri::from_str(input)?; + + let scheme = uri.scheme().ok_or(ClientInitError::InvalidScheme)?; + + // Check the scheme if necessary + if let Some(correct_scheme) = correct_scheme { + if scheme != correct_scheme { + return Err(ClientInitError::InvalidScheme); + } + } + + let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; + let port = uri.port().map(|x| format!(":{}", x)).unwrap_or_default(); + Ok(format!("{}://{}{}", scheme, host, port)) +} + +/// A client that implements the API by making HTTP calls out to a server. +#[derive(Clone)] +pub struct Client { + hyper_client: Arc Box, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>> + Sync + Send>, + handle: Arc, + base_path: String, +} + +impl fmt::Debug for Client { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Client {{ base_path: {} }}", self.base_path) + } +} + +impl Client { + + /// Create an HTTP client. + /// + /// # Arguments + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + pub fn try_new_http(handle: Handle, base_path: &str) -> Result { + let http_connector = swagger::http_connector(); + Self::try_new_with_connector::( + handle, + base_path, + Some("http"), + http_connector, + ) + } + + /// Create a client with a TLS connection to the server. + /// + /// # Arguments + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + /// * `ca_certificate` - Path to CA certificate used to authenticate the server + pub fn try_new_https( + handle: Handle, + base_path: &str, + ca_certificate: CA, + ) -> Result + where + CA: AsRef, + { + let https_connector = swagger::https_connector(ca_certificate); + Self::try_new_with_connector::>( + handle, + base_path, + Some("https"), + https_connector, + ) + } + + /// Create a client with a mutually authenticated TLS connection to the server. + /// + /// # Arguments + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + /// * `ca_certificate` - Path to CA certificate used to authenticate the server + /// * `client_key` - Path to the client private key + /// * `client_certificate` - Path to the client's public certificate associated with the private key + pub fn try_new_https_mutual( + handle: Handle, + base_path: &str, + ca_certificate: CA, + client_key: K, + client_certificate: C, + ) -> Result + where + CA: AsRef, + K: AsRef, + C: AsRef, + { + let https_connector = + swagger::https_mutual_connector(ca_certificate, client_key, client_certificate); + Self::try_new_with_connector::>( + handle, + base_path, + Some("https"), + https_connector, + ) + } + + /// Create a client with a custom implementation of hyper::client::Connect. + /// + /// Intended for use with custom implementations of connect for e.g. protocol logging + /// or similar functionality which requires wrapping the transport layer. When wrapping a TCP connection, + /// this function should be used in conjunction with + /// `swagger::{http_connector, https_connector, https_mutual_connector}`. + /// + /// For ordinary tcp connections, prefer the use of `try_new_http`, `try_new_https` + /// and `try_new_https_mutual`, to avoid introducing a dependency on the underlying transport layer. + /// + /// # Arguments + /// + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + /// * `protocol` - Which protocol to use when constructing the request url, e.g. `Some("http")` + /// * `connector_fn` - Function which returns an implementation of `hyper::client::Connect` + pub fn try_new_with_connector( + handle: Handle, + base_path: &str, + protocol: Option<&'static str>, + connector_fn: Box C + Send + Sync>, + ) -> Result + where + C: hyper::client::Connect + hyper::client::Service, + { + let hyper_client = { + move |handle: &Handle| -> Box< + hyper::client::Service< + Request = hyper::Request, + Response = hyper::Response, + Error = hyper::Error, + Future = hyper::client::FutureResponse, + >, + > { + let connector = connector_fn(handle); + Box::new(hyper::Client::configure().connector(connector).build( + handle, + )) + } + }; + + Ok(Client { + hyper_client: Arc::new(hyper_client), + handle: Arc::new(handle), + base_path: into_base_path(base_path, protocol)?, + }) + } + + /// Constructor for creating a `Client` by passing in a pre-made `hyper` client. + /// + /// One should avoid relying on this function if possible, since it adds a dependency on the underlying transport + /// implementation, which it would be better to abstract away. Therefore, using this function may lead to a loss of + /// code generality, which may make it harder to move the application to a serverless environment, for example. + /// + /// The reason for this function's existence is to support legacy test code, which did mocking at the hyper layer. + /// This is not a recommended way to write new tests. If other reasons are found for using this function, they + /// should be mentioned here. + pub fn try_new_with_hyper_client(hyper_client: Arc Box, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>> + Sync + Send>, + handle: Handle, + base_path: &str) + -> Result + { + Ok(Client { + hyper_client: hyper_client, + handle: Arc::new(handle), + base_path: into_base_path(base_path, None)?, + }) + } +} + +impl Api for Client { +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, param_{{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box> { +{{#queryParams}}{{#-first}} + // Query parameters +{{/-first}}{{#required}} let query_{{paramName}} = format!("{{baseName}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{paramName}}=param_{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}}); +{{/required}}{{^required}} let query_{{paramName}} = param_{{paramName}}.map_or_else(String::new, |query| format!("{{baseName}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{paramName}}=query{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}})); +{{/required}}{{/queryParams}} + + let uri = format!( + "{}{{basePathWithoutHost}}{{path}}{{#queryParams}}{{#-first}}?{{/-first}}{{=<% %>=}}{<% paramName %>}<%={{ }}=%>{{/queryParams}}", + self.base_path{{#pathParams}}, {{baseName}}=utf8_percent_encode(¶m_{{paramName}}.to_string(), PATH_SEGMENT_ENCODE_SET){{/pathParams}}{{#queryParams}}, + {{paramName}}=utf8_percent_encode(&query_{{paramName}}, QUERY_ENCODE_SET){{/queryParams}} + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::{{#vendorExtensions}}{{HttpMethod}}{{/vendorExtensions}}, uri); + +{{#vendorExtensions}}{{#hasFile}} // Form data body + let mut multipart = Multipart::new(); + + // Helper function to convert a Stream into a String. The String can then be used to build the HTTP body. + fn convert_stream_to_string(stream: Box, Error=Error> + Send>) -> Result { + + stream.concat2() + .wait() + .map_err(|e| ApiError(format!("Unable to collect stream: {}", e))) + .and_then(|body| String::from_utf8(body) + .map_err(|e| ApiError(format!("Failed to convert utf8 stream to String: {}", e)))) + }{{/hasFile}}{{/vendorExtensions}}{{#formParams}}{{#isFile}} + +{{^required}} if let Ok(Some(param_{{paramName}})) = param_{{paramName}}.wait() { {{/required}} +{{^required}} {{/required}} match convert_stream_to_string(param_{{paramName}}) { +{{^required}} {{/required}} Ok(param_{{paramName}}) => { + // Add file to multipart form. + multipart.add_text("{{paramName}}", param_{{paramName}}); + }, +{{^required}} {{/required}} Err(err) => return Box::new(futures::done(Err(err))), +{{^required}} {{/required}} } + {{^required}}}{{/required}}{{/isFile}}{{/formParams}}{{#vendorExtensions}}{{#hasFile}} + + let mut fields = match multipart.prepare() { + Ok(fields) => fields, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build request: {}", err))))), + }; + + let mut body_string = String::new(); + let body = fields.to_body().read_to_string(&mut body_string); + let boundary = fields.boundary(); + let multipart_header = match mime::Mime::from_str(&format!("multipart/form-data;boundary={}", boundary)) { + Ok(multipart_header) => multipart_header, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build multipart header: {:?}", err))))), + };{{/hasFile}}{{^hasFile}}{{#formParams}}{{#-first}} let params = &[{{/-first}} + ("{{baseName}}", {{#vendorExtensions}}{{#required}}Some({{#isString}}param_{{paramName}}{{/isString}}{{^isString}}format!("{:?}", param_{{paramName}}){{/isString}}){{/required}}{{^required}}{{#isString}}param_{{paramName}}{{/isString}}{{^isString}}param_{{paramName}}.map(|param| format!("{:?}", param)){{/isString}}{{/required}}),{{/vendorExtensions}}{{#-last}} + ]; + let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize"); + + request.headers_mut().set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}.clone())); + request.set_body(body.into_bytes());{{/-last}}{{/formParams}}{{/hasFile}}{{/vendorExtensions}}{{#bodyParam}}{{#-first}} + // Body parameter +{{/-first}}{{#vendorExtensions}}{{#required}}{{#consumesPlainText}} let body = param_{{paramName}};{{/consumesPlainText}}{{#consumesXml}} +{{^has_namespace}} let body = serde_xml_rs::to_string(¶m_{{paramName}}).expect("impossible to fail to serialize");{{/has_namespace}}{{#has_namespace}} + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); + let body = serde_xml_rs::to_string_with_namespaces(¶m_{{paramName}}, namespaces).expect("impossible to fail to serialize");{{/has_namespace}}{{/consumesXml}}{{#consumesJson}} + let body = serde_json::to_string(¶m_{{paramName}}).expect("impossible to fail to serialize");{{/consumesJson}} +{{/required}}{{^required}}{{#consumesPlainText}} let body = param_{{paramName}}; +{{/consumesPlainText}}{{^consumesPlainText}} let body = param_{{paramName}}.map(|ref body| { +{{#consumesXml}} +{{^has_namespace}} serde_xml_rs::to_string(body).expect("impossible to fail to serialize"){{/has_namespace}}{{#has_namespace}} + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); + serde_xml_rs::to_string_with_namespaces(body, namespaces).expect("impossible to fail to serialize"){{/has_namespace}}{{/consumesXml}}{{#consumesJson}} + serde_json::to_string(body).expect("impossible to fail to serialize"){{/consumesJson}} + });{{/consumesPlainText}}{{/required}}{{/vendorExtensions}}{{/bodyParam}} + +{{#bodyParam}}{{^required}}if let Some(body) = body { + {{/required}} request.set_body(body.into_bytes()); +{{^required}} }{{/required}} + + request.headers_mut().set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}.clone())); +{{/bodyParam}} + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); +{{#authMethods}}{{#isBasic}} context.auth_data.as_ref().map(|auth_data| { + if let &swagger::AuthData::Basic(ref basic_header) = auth_data { + request.headers_mut().set(hyper::header::Authorization( + basic_header.clone(), + )) + } + });{{/isBasic}}{{/authMethods}}{{#headerParams}}{{#-first}} + // Header parameters +{{/-first}}{{^isMapContainer}} header! { (Request{{vendorExtensions.typeName}}, "{{baseName}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} } +{{#required}} request.headers_mut().set(Request{{vendorExtensions.typeName}}(param_{{paramName}}{{#isListContainer}}.clone(){{/isListContainer}})); +{{/required}}{{^required}} param_{{paramName}}.map(|header| request.headers_mut().set(Request{{vendorExtensions.typeName}}(header{{#isListContainer}}.clone(){{/isListContainer}}))); +{{/required}}{{/isMapContainer}}{{#isMapContainer}} let param_{{paramName}}: Option<{{{dataType}}}> = None; +{{/isMapContainer}}{{/headerParams}} + +{{#vendorExtensions}}{{#hasFile}} + request.headers_mut().set(ContentType(multipart_header)); + request.set_body(body_string.into_bytes()); +{{/hasFile}}{{/vendorExtensions}} + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { +{{#responses}} + {{code}} => { +{{#headers}} header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{datatype}}}] } + let response_{{name}} = match response.headers().get::() { + Some(response_{{name}}) => response_{{name}}.0.clone(), + None => return Box::new(future::err(ApiError(String::from("Required response header {{baseName}} for response {{code}} was not found.")))) as Box>, + }; +{{/headers}} + {{^isFile}}let body = response.body();{{/isFile}}{{#isFile}}let body = Box::new(response.body() + .map(|chunk| chunk.to_vec()) + .map_err(|_| + Error::new(ErrorKind::Other, "Received error reading response.") + ));{{/isFile}} + Box::new( +{{#dataType}}{{^isFile}} + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| +{{#vendorExtensions}}{{#producesXml}} + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + serde_xml_rs::from_str::<{{{dataType}}}>(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e))) +{{/producesXml}}{{#producesJson}} + serde_json::from_str::<{{{dataType}}}>(body) + .map_err(|e| e.into()) +{{/producesJson}}{{#producesPlainText}} + Ok(body.to_string()) +{{/producesPlainText}}{{/vendorExtensions}} + )) + .map(move |body| +{{/isFile}}{{#isFile}} + future::ok( +{{/isFile}} + {{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}{{^headers}}(body){{/headers}}{{#headers}}{{#-first}}{ body: body, {{/-first}}{{name}}: response_{{name}}{{^-last}}, {{/-last}}{{#-last}} }{{/-last}}{{/headers}} + ) +{{/dataType}}{{^dataType}} + future::ok( + {{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}{{#headers}}{{#-first}}{ {{/-first}}{{^-first}}, {{/-first}}{{name}}: response_{{name}}{{#-last}} }{{/-last}}{{/headers}} + ) +{{/dataType}} + ) as Box> + }, +{{/responses}} + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +} + +#[derive(Debug)] +pub enum ClientInitError { + InvalidScheme, + InvalidUri(hyper::error::UriError), + MissingHost, + SslError(openssl::error::ErrorStack) +} + +impl From for ClientInitError { + fn from(err: hyper::error::UriError) -> ClientInitError { + ClientInitError::InvalidUri(err) + } +} + +impl From for ClientInitError { + fn from(err: openssl::error::ErrorStack) -> ClientInitError { + ClientInitError::SslError(err) + } +} + +impl fmt::Display for ClientInitError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + (self as &fmt::Debug).fmt(f) + } +} + +impl error::Error for ClientInitError { + fn description(&self) -> &str { + "Failed to produce a hyper client." + } +} diff --git a/modules/openapi-generator/src/main/resources/rust-server/client.mustache b/modules/openapi-generator/src/main/resources/rust-server/client.mustache deleted file mode 100644 index 2d9e7b18d5e8..000000000000 --- a/modules/openapi-generator/src/main/resources/rust-server/client.mustache +++ /dev/null @@ -1,342 +0,0 @@ -#![allow(unused_extern_crates)] -extern crate hyper_openssl; -extern crate chrono; -extern crate url; -{{#apiHasFile}}extern crate multipart;{{/apiHasFile}} - -{{#apiHasFile}}use multipart::client::lazy::Multipart;{{/apiHasFile}} -use hyper; -use hyper::client::IntoUrl; -use hyper::mime; -use hyper::header::{Headers, ContentType}; -use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; -use hyper::Url; -use self::hyper_openssl::openssl; -use self::url::percent_encoding::{utf8_percent_encode, PATH_SEGMENT_ENCODE_SET, QUERY_ENCODE_SET}; -use futures; -use futures::{Future, Stream}; -use futures::{future, stream}; -use std::borrow::Cow; -use std::io::{Read, Error}; -use std::error; -use std::fmt; -use std::path::Path; -use std::sync::Arc; -use std::str; - -use mimetypes; - -use serde_json; -{{#usesXml}}use serde_xml_rs;{{/usesXml}} - -#[allow(unused_imports)] -use std::collections::{HashMap, BTreeMap}; -#[allow(unused_imports)] -use swagger; - -use swagger::{Context, ApiError, XSpanId}; - -use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, - {{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} - }; -use models; - -/// Convert input into a base path, e.g. "http://example:123". Also checks the scheme as it goes. -fn into_base_path(input: T, correct_scheme: Option<&'static str>) -> Result { - // First convert to Url, since a base path is a subset of Url. - let url = input.into_url()?; - - let scheme = url.scheme(); - - // Check the scheme if necessary - if let Some(correct_scheme) = correct_scheme { - if scheme != correct_scheme { - return Err(ClientInitError::InvalidScheme); - } - } - - let host = url.host().ok_or_else(|| ClientInitError::MissingHost)?; - let port = url.port().map(|x| format!(":{}", x)).unwrap_or_default(); - Ok(format!("{}://{}{}", scheme, host, port)) -} - -/// A client that implements the API by making HTTP calls out to a server. -#[derive(Clone)] -pub struct Client { - base_path: String, - hyper_client: Arc hyper::client::Client + Sync + Send>, -} - -impl fmt::Debug for Client { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Client {{ base_path: {} }}", self.base_path) - } -} - -impl Client { - pub fn try_new_http(base_path: T) -> Result - where T: IntoUrl - { - Ok(Client { - base_path: into_base_path(base_path, Some("http"))?, - hyper_client: Arc::new(hyper::client::Client::new), - }) - } - - pub fn try_new_https(base_path: T, - ca_certificate: CA) - -> Result - where T: IntoUrl, - CA: AsRef - { - let ca_certificate = ca_certificate.as_ref().to_owned(); - - let https_hyper_client = move || { - // SSL implementation - let mut ssl = openssl::ssl::SslConnectorBuilder::new(openssl::ssl::SslMethod::tls()).unwrap(); - - // Server authentication - ssl.set_ca_file(ca_certificate.clone()).unwrap(); - - let ssl = hyper_openssl::OpensslClient::from(ssl.build()); - let connector = hyper::net::HttpsConnector::new(ssl); - hyper::client::Client::with_connector(connector) - }; - - Ok(Client { - base_path: into_base_path(base_path, Some("https"))?, - hyper_client: Arc::new(https_hyper_client), - }) - } - - pub fn try_new_https_mutual(base_path: T, - ca_certificate: CA, - client_key: K, - client_certificate: C) - -> Result - where T: IntoUrl, - CA: AsRef, - K: AsRef, - C: AsRef - { - let ca_certificate = ca_certificate.as_ref().to_owned(); - let client_key = client_key.as_ref().to_owned(); - let client_certificate = client_certificate.as_ref().to_owned(); - - let https_mutual_hyper_client = move || { - // SSL implementation - let mut ssl = openssl::ssl::SslConnectorBuilder::new(openssl::ssl::SslMethod::tls()).unwrap(); - - // Server authentication - ssl.set_ca_file(ca_certificate.clone()).unwrap(); - - // Client authentication - ssl.set_private_key_file(client_key.clone(), openssl::x509::X509_FILETYPE_PEM).unwrap(); - ssl.set_certificate_chain_file(client_certificate.clone()).unwrap(); - ssl.check_private_key().unwrap(); - - let ssl = hyper_openssl::OpensslClient::from(ssl.build()); - let connector = hyper::net::HttpsConnector::new(ssl); - hyper::client::Client::with_connector(connector) - }; - - Ok(Client { - base_path: into_base_path(base_path, Some("https"))?, - hyper_client: Arc::new(https_mutual_hyper_client) - }) - } - - /// Constructor for creating a `Client` by passing in a pre-made `hyper` client. - /// - /// One should avoid relying on this function if possible, since it adds a dependency on the underlying transport - /// implementation, which it would be better to abstract away. Therefore, using this function may lead to a loss of - /// code generality, which may make it harder to move the application to a serverless environment, for example. - /// - /// The reason for this function's existence is to support legacy test code, which did mocking at the hyper layer. - /// This is not a recommended way to write new tests. If other reasons are found for using this function, they - /// should be mentioned here. - pub fn try_new_with_hyper_client(base_path: T, - hyper_client: Arc hyper::client::Client + Sync + Send>) - -> Result - where T: IntoUrl - { - Ok(Client { - base_path: into_base_path(base_path, None)?, - hyper_client: hyper_client - }) - } -} - -impl Api for Client { -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} - fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, param_{{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box + Send> { -{{#queryParams}}{{#-first}} - // Query parameters -{{/-first}}{{#required}} let query_{{paramName}} = format!("{{baseName}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{paramName}}=param_{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}}); -{{/required}}{{^required}} let query_{{paramName}} = param_{{paramName}}.map_or_else(String::new, |query| format!("{{baseName}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{paramName}}=query{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}})); -{{/required}}{{/queryParams}} - - let url = format!( - "{}{{basePathWithoutHost}}{{path}}{{#queryParams}}{{#-first}}?{{/-first}}{{=<% %>=}}{<% paramName %>}<%={{ }}=%>{{/queryParams}}", - self.base_path{{#pathParams}}, {{baseName}}=utf8_percent_encode(¶m_{{paramName}}.to_string(), PATH_SEGMENT_ENCODE_SET){{/pathParams}}{{#queryParams}}, - {{paramName}}=utf8_percent_encode(&query_{{paramName}}, QUERY_ENCODE_SET){{/queryParams}} - ); - -{{#vendorExtensions}}{{#hasFile}} // Form data body - let mut multipart = Multipart::new();{{/hasFile}}{{/vendorExtensions}}{{#formParams}}{{#isFile}} - -{{^required}} if let Ok(Some(param_{{paramName}})) = param_{{paramName}}.wait() { {{/required}} -{{^required}} {{/required}} match convert_stream_to_string(param_{{paramName}}) { -{{^required}} {{/required}} Ok(param_{{paramName}}) => { - // Add file to multipart form. - multipart.add_text("{{paramName}}", param_{{paramName}}); - }, -{{^required}} {{/required}} Err(err) => return Box::new(futures::done(Err(err))), -{{^required}} {{/required}} } - {{^required}}}{{/required}}{{/isFile}}{{/formParams}}{{#vendorExtensions}}{{#hasFile}} - - let mut fields = match multipart.prepare() { - Ok(fields) => fields, - Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build request: {}", err))))), - }; - - let mut body_string = String::new(); - let body = fields.to_body().read_to_string(&mut body_string); - let boundary = fields.boundary(); - let multipart_header = Mime(TopLevel::Multipart, SubLevel::FormData, vec![(Attr::Boundary, Value::Ext(boundary.to_string()))]);{{/hasFile}}{{/vendorExtensions}}{{#bodyParam}}{{#-first}} - // Body parameter -{{/-first}}{{#vendorExtensions}}{{#required}}{{#consumesPlainText}} let body = param_{{paramName}};{{/consumesPlainText}}{{#consumesXml}} -{{^has_namespace}} let body = serde_xml_rs::to_string(¶m_{{paramName}}).expect("impossible to fail to serialize");{{/has_namespace}}{{#has_namespace}} - let mut namespaces = BTreeMap::new(); - // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); - let body = serde_xml_rs::to_string_with_namespaces(¶m_{{paramName}}, namespaces).expect("impossible to fail to serialize");{{/has_namespace}}{{/consumesXml}}{{#consumesJson}} - let body = serde_json::to_string(¶m_{{paramName}}).expect("impossible to fail to serialize");{{/consumesJson}} -{{/required}}{{^required}}{{#consumesPlainText}} let body = param_{{paramName}}; -{{/consumesPlainText}}{{^consumesPlainText}} let body = param_{{paramName}}.map(|ref body| { -{{#consumesXml}} -{{^has_namespace}} serde_xml_rs::to_string(body).expect("impossible to fail to serialize"){{/has_namespace}}{{#has_namespace}} - let mut namespaces = BTreeMap::new(); - // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); - serde_xml_rs::to_string_with_namespaces(body, namespaces).expect("impossible to fail to serialize"){{/has_namespace}}{{/consumesXml}}{{#consumesJson}} - serde_json::to_string(body).expect("impossible to fail to serialize"){{/consumesJson}} - });{{/consumesPlainText}}{{/required}}{{/vendorExtensions}}{{/bodyParam}} - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::{{#vendorExtensions}}{{HttpMethod}}{{/vendorExtensions}}, &url); - let mut custom_headers = hyper::header::Headers::new(); - -{{#bodyParam}}{{#required}} let request = request.body(&body); -{{/required}}{{^required}} let request = match body { - Some(ref body) => request.body(body), - None => request, - }; -{{/required}} - - custom_headers.set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}.clone())); -{{/bodyParam}} - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); -{{#headerParams}}{{#-first}} - // Header parameters -{{/-first}}{{^isMapContainer}} header! { (Request{{vendorExtensions.typeName}}, "{{baseName}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} } -{{#required}} custom_headers.set(Request{{vendorExtensions.typeName}}(param_{{paramName}}{{#isListContainer}}.clone(){{/isListContainer}})); -{{/required}}{{^required}} param_{{paramName}}.map(|header| custom_headers.set(Request{{vendorExtensions.typeName}}(header{{#isListContainer}}.clone(){{/isListContainer}}))); -{{/required}}{{/isMapContainer}}{{#isMapContainer}} let param_{{paramName}}: Option<{{{dataType}}}> = None; -{{/isMapContainer}}{{/headerParams}} - - let request = request.headers(custom_headers);{{#vendorExtensions}}{{#hasFile}} - let request = request.header(ContentType(multipart_header)) - .body(&body_string); -{{/hasFile}}{{/vendorExtensions}} - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result<{{operationId}}Response, ApiError> { - match response.status.to_u16() { -{{#responses}} - {{code}} => { -{{#dataType}}{{^isFile}} let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?;{{#vendorExtensions}}{{#producesXml}} - // ToDo: this will move to swagger-rs and become a standard From conversion trait - // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream - let body = serde_xml_rs::from_str::<{{{dataType}}}>(&buf) - .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?;{{/producesXml}}{{#producesPlainText}} - let body = buf;{{/producesPlainText}}{{#producesJson}} - let body = serde_json::from_str::<{{{dataType}}}>(&buf)?;{{/producesJson}}{{/vendorExtensions}}{{/isFile}}{{#isFile}} - let mut buf = Vec::new(); - response.read_to_end(&mut buf).map_err(|e| ApiError(format!("Received error reading response: {}", e)))?; - let body = Box::new(stream::once(Ok(buf)));{{/isFile}}{{/dataType}} -{{#headers}} header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{datatype}}}] } - let response_{{name}} = response.headers.get::().ok_or_else(|| "Required response header {{baseName}} for response {{code}} was not found.")?; -{{/headers}} - -{{#dataType}} Ok({{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}{{^headers}}(body){{/headers}}{{#headers}}{{#-first}}{ body: body, {{/-first}}{{name}}: response_{{name}}.0.clone(){{^-last}}, {{/-last}}{{#-last}} }{{/-last}}{{/headers}}) -{{/dataType}}{{^dataType}} Ok({{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}{{#headers}}{{#-first}}{ {{/-first}}{{^-first}}, {{/-first}}{{name}}: response_{{name}}.0.clone(){{#-last}} }{{/-last}}{{/headers}}) -{{/dataType}} - }, -{{/responses}} - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - }{{#vendorExtensions}}{{#hasFile}} - - // Helper function to convert a Stream into a String. The String can then be used to build the HTTP body. - fn convert_stream_to_string(stream: Box, Error=Error> + Send>) -> Result { - - stream.fold(Vec::new(), |mut body, chunk| { - body.extend(chunk.iter()); - future::ok::,Error>(body) - }).wait() - .map_err(|e| ApiError(format!("Unable to fold stream: {}", e))) - .and_then(|body| String::from_utf8(body) - .map_err(|e| ApiError(format!("Failed to convert utf8 stream to String: {}", e)))) - }{{/hasFile}}{{/vendorExtensions}} - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } -{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} -} - -#[derive(Debug)] -pub enum ClientInitError { - InvalidScheme, - InvalidUrl(hyper::error::ParseError), - MissingHost, - SslError(openssl::error::ErrorStack) -} - -impl From for ClientInitError { - fn from(err: hyper::error::ParseError) -> ClientInitError { - ClientInitError::InvalidUrl(err) - } -} - -impl From for ClientInitError { - fn from(err: openssl::error::ErrorStack) -> ClientInitError { - ClientInitError::SslError(err) - } -} - -impl fmt::Display for ClientInitError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - (self as &fmt::Debug).fmt(f) - } -} - -impl error::Error for ClientInitError { - fn description(&self) -> &str { - "Failed to produce a hyper client." - } -} diff --git a/modules/openapi-generator/src/main/resources/rust-server/example-client.mustache b/modules/openapi-generator/src/main/resources/rust-server/example-client.mustache index e5b59e5c4f94..2245ae475628 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/example-client.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/example-client.mustache @@ -8,9 +8,11 @@ extern crate swagger; #[allow(unused_extern_crates)] extern crate uuid; extern crate clap; +extern crate tokio_core; #[allow(unused_imports)] use futures::{Future, future, Stream, stream}; +use tokio_core::reactor; #[allow(unused_imports)] use {{externCrateName}}::{ApiNoContext, ContextWrapperExt, ApiError{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, @@ -42,18 +44,19 @@ fn main() { .help("Port to contact")) .get_matches(); + let mut core = reactor::Core::new().unwrap(); let is_https = matches.is_present("https"); let base_url = format!("{}://{}:{}", if is_https { "https" } else { "http" }, matches.value_of("host").unwrap(), matches.value_of("port").unwrap()); - let client = if is_https { + let client = if matches.is_present("https") { // Using Simple HTTPS - {{externCrateName}}::Client::try_new_https(&base_url, "examples/ca.pem") + {{externCrateName}}::Client::try_new_https(core.handle(), &base_url, "examples/ca.pem") .expect("Failed to create HTTPS client") } else { // Using HTTP - {{externCrateName}}::Client::try_new_http(&base_url) + {{externCrateName}}::Client::try_new_http(core.handle(), &base_url) .expect("Failed to create HTTP client") }; @@ -64,7 +67,7 @@ fn main() { {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#vendorExtensions}}{{#noClientExample}}// Disabled because there's no example. // {{/noClientExample}}Some("{{operationId}}") => { - {{#noClientExample}}// {{/noClientExample}} let result = client.{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{^-first}}, {{/-first}}{{#vendorExtensions}}{{{example}}}{{/vendorExtensions}}{{/allParams}}).wait(); + {{#noClientExample}}// {{/noClientExample}} let result = core.run(client.{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{^-first}}, {{/-first}}{{#vendorExtensions}}{{{example}}}{{/vendorExtensions}}{{/allParams}})); {{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); {{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} }, {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/example-server.mustache b/modules/openapi-generator/src/main/resources/rust-server/example-server.mustache index 007384b33feb..ee99d434bb36 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/example-server.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/example-server.mustache @@ -6,8 +6,11 @@ // extern crate ; extern crate {{externCrateName}}; extern crate swagger; -extern crate iron; -extern crate hyper_openssl; +extern crate hyper; +extern crate openssl; +extern crate native_tls; +extern crate tokio_proto; +extern crate tokio_tls; extern crate clap; // Imports required by server library. @@ -17,19 +20,20 @@ extern crate futures; extern crate chrono; #[macro_use] extern crate error_chain; +{{#apiUsesUuid}}extern crate uuid;{{/apiUsesUuid}} -use hyper_openssl::OpensslServer; -use hyper_openssl::openssl::x509::X509_FILETYPE_PEM; -use hyper_openssl::openssl::ssl::{SslAcceptorBuilder, SslMethod}; -use hyper_openssl::openssl::error::ErrorStack; +use openssl::x509::X509_FILETYPE_PEM; +use openssl::ssl::{SslAcceptorBuilder, SslMethod}; +use openssl::error::ErrorStack; +use hyper::server::Http; +use tokio_proto::TcpServer; use clap::{App, Arg}; -use iron::{Iron, Chain}; -use swagger::auth::AllowAllMiddleware; +use swagger::auth::AllowAllAuthenticator; mod server_lib; -/// Builds an SSL implementation for Simple HTTPS from some hard-coded file names -fn ssl() -> Result { +// Builds an SSL implementation for Simple HTTPS from some hard-coded file names +fn ssl() -> Result { let mut ssl = SslAcceptorBuilder::mozilla_intermediate_raw(SslMethod::tls())?; // Server authentication @@ -37,7 +41,7 @@ fn ssl() -> Result { ssl.set_certificate_chain_file("examples/server-chain.pem")?; ssl.check_private_key()?; - Ok(OpensslServer::from(ssl.build())) + Ok(ssl) } /// Create custom server, wire it to the autogenerated router, @@ -49,20 +53,22 @@ fn main() { .help("Whether to use HTTPS or not")) .get_matches(); - let server = server_lib::server().unwrap(); - let router = {{externCrateName}}::router(server); - - let mut chain = Chain::new(router); - chain.link_before({{externCrateName}}::server::ExtractAuthData); - // add authentication middlewares into the chain here - // for the purpose of this example, pretend we have authenticated a user - chain.link_before(AllowAllMiddleware::new("cosmo")); + let service_fn = + {{externCrateName}}::server::auth::NewService::new( + AllowAllAuthenticator::new( + server_lib::NewService, + "cosmo" + ) + ); + let addr = "127.0.0.1:{{serverPort}}".parse().expect("Failed to parse bind address"); if matches.is_present("https") { - // Using Simple HTTPS - Iron::new(chain).https("localhost:{{serverPort}}", ssl().expect("Failed to load SSL keys")).expect("Failed to start HTTPS server"); + let ssl = ssl().expect("Failed to load SSL keys"); + let builder: native_tls::TlsAcceptorBuilder = native_tls::backend::openssl::TlsAcceptorBuilderExt::from_openssl(ssl); + let tls_acceptor = builder.build().expect("Failed to build TLS acceptor"); + TcpServer::new(tokio_tls::proto::Server::new(Http::new(), tls_acceptor), addr).serve(service_fn); } else { // Using HTTP - Iron::new(chain).http("localhost:{{serverPort}}").expect("Failed to start HTTP server"); + TcpServer::new(Http::new(), addr).serve(service_fn); } } diff --git a/modules/openapi-generator/src/main/resources/rust-server/example-server_lib.mustache b/modules/openapi-generator/src/main/resources/rust-server/example-server_lib.mustache index 7e85ec86199d..d02d0525b47c 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/example-server_lib.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/example-server_lib.mustache @@ -7,8 +7,20 @@ mod errors { } pub use self::errors::*; +use std::io; +use hyper; +use {{externCrateName}}; -/// Instantiate a new server. -pub fn server() -> Result { - Ok(server::Server {}) +pub struct NewService; + +impl hyper::server::NewService for NewService { + type Request = (hyper::Request, {{externCrateName}}::Context); + type Response = hyper::Response; + type Error = hyper::Error; + type Instance = {{externCrateName}}::server::Service; + + /// Instantiate a new server. + fn new_service(&self) -> io::Result { + Ok({{externCrateName}}::server::Service::new(server::Server)) + } } diff --git a/modules/openapi-generator/src/main/resources/rust-server/example-server_server.mustache b/modules/openapi-generator/src/main/resources/rust-server/example-server_server.mustache index 8b8bf033927b..fdb7ceaf541d 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/example-server_server.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/example-server_server.mustache @@ -7,6 +7,7 @@ use chrono; {{#apiHasFile}}use futures::Stream;{{/apiHasFile}} use std::collections::HashMap; {{#apiHasFile}}use std::io::Error;{{/apiHasFile}} +{{#apiUsesUuid}}use uuid;{{/apiUsesUuid}} use swagger; use {{externCrateName}}::{Api, ApiError, Context{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, @@ -20,7 +21,7 @@ pub struct Server; impl Api for Server { {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#summary}} /// {{{summary}}}{{/summary}} - fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box + Send> { + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box> { let context = context.clone(); println!("{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{^isFile}}{{#vendorExtensions}}{{{formatString}}}{{/vendorExtensions}}{{#hasMore}}, {{/hasMore}}{{/isFile}}{{/allParams}}) - X-Span-ID: {:?}"{{#allParams}}{{^isFile}}, {{paramName}}{{/isFile}}{{/allParams}}, context.x_span_id.unwrap_or(String::from("")).clone());{{#allParams}}{{#isFile}} let _ = {{paramName}}; //Suppresses unused param warning{{/isFile}}{{/allParams}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/lib.mustache b/modules/openapi-generator/src/main/resources/rust-server/lib.mustache index 0ab6543fcfc9..6c54cdda649f 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/lib.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/lib.mustache @@ -3,10 +3,10 @@ extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; +{{#apiUsesUuid}}extern crate uuid;{{/apiUsesUuid}} {{#usesXml}}extern crate serde_xml_rs;{{/usesXml}} extern crate futures; extern crate chrono; -{{#apiHasFile}}extern crate multipart;{{/apiHasFile}} #[macro_use] extern crate lazy_static; #[macro_use] @@ -32,6 +32,9 @@ mod mimetypes; pub use swagger::{ApiError, Context, ContextWrapper}; +pub const BASE_PATH: &'static str = "{{basePathWithoutHost}}"; +pub const API_VERSION: &'static str = "{{appVersion}}"; + {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{^isResponseFile}} #[derive(Debug, PartialEq)] @@ -48,7 +51,7 @@ pub enum {{operationId}}Response { pub trait Api { {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#summary}} /// {{{summary}}}{{/summary}} - fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box + Send>; + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box>; {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} } @@ -56,7 +59,7 @@ pub trait Api { pub trait ApiNoContext { {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#summary}} /// {{{summary}}}{{/summary}} - fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}) -> Box + Send>; + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}) -> Box>; {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} } @@ -75,7 +78,7 @@ impl<'a, T: Api + Sized> ContextWrapperExt<'a> for T { impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> { {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#summary}} /// {{{summary}}}{{/summary}} - fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}) -> Box + Send> { + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}) -> Box> { self.api().{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{paramName}}, {{/allParams}}&self.context()) } {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} @@ -93,6 +96,6 @@ pub mod server; // Re-export router() as a top-level name #[cfg(feature = "server")] -pub use self::server::router; +pub use self::server::Service; pub mod models; diff --git a/modules/openapi-generator/src/main/resources/rust-server/mimetypes.mustache b/modules/openapi-generator/src/main/resources/rust-server/mimetypes.mustache index 744374ca9955..047c7c7fbbce 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/mimetypes.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/mimetypes.mustache @@ -15,7 +15,11 @@ pub mod requests { use hyper::mime::*; {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#bodyParam}} /// Create Mime objects for the request content types for {{operationId}} lazy_static! { - pub static ref {{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}: Mime = "{{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}{{^consumes}}Application/Json{{/consumes}}".parse().unwrap(); + pub static ref {{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}: Mime = "{{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}{{^consumes}}application/json{{/consumes}}".parse().unwrap(); } -{{/bodyParam}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +{{/bodyParam}}{{^bodyParam}}{{#vendorExtensions}}{{#formParams}}{{#-first}}{{^hasFile}} /// Create Mime objects for the request content types for {{operationId}} + lazy_static! { + pub static ref {{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}: Mime = "{{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}{{^consumes}}application/x-www-form-urlencoded{{/consumes}}".parse().unwrap(); + } +{{/hasFile}}{{/-first}}{{/formParams}}{{/vendorExtensions}}{{/bodyParam}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} } diff --git a/modules/openapi-generator/src/main/resources/rust-server/models.mustache b/modules/openapi-generator/src/main/resources/rust-server/models.mustache old mode 100755 new mode 100644 diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-auth.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-auth.mustache new file mode 100644 index 000000000000..5f2884cf8aad --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-server/server-auth.mustache @@ -0,0 +1,95 @@ +use std::io; +use hyper; +use hyper::{Request, Response, Error, StatusCode}; +use server::url::form_urlencoded; +use swagger::auth::{Authorization, AuthData, Scopes}; +use Api; + +pub struct NewService where T: hyper::server::NewService), Response=Response, Error=Error> { + inner: T, +} + +impl NewService where T: hyper::server::NewService), Response=Response, Error=Error> + 'static { + pub fn new(inner: T) -> NewService { + NewService{inner} + } +} + +impl hyper::server::NewService for NewService where T: hyper::server::NewService), Response=Response, Error=Error> + 'static { + type Request = Request; + type Response = Response; + type Error = Error; + type Instance = Service; + + fn new_service(&self) -> Result { + self.inner.new_service().map(|s| Service::new(s)) + } +} + +/// Middleware to extract authentication data from request +pub struct Service where T: hyper::server::Service), Response=Response, Error=Error> { + inner: T, +} + +impl Service where T: hyper::server::Service), Response=Response, Error=Error> { + pub fn new(inner: T) -> Service { + Service{inner} + } +} + +impl hyper::server::Service for Service where T: hyper::server::Service), Response=Response, Error=Error> { + type Request = Request; + type Response = Response; + type Error = Error; + type Future = T::Future; + + fn call(&self, req: Self::Request) -> Self::Future { + {{#authMethods}} + {{#isBasic}} + { + use hyper::header::{Authorization, Basic, Bearer}; + use std::ops::Deref; + if let Some(basic) = req.headers().get::>().cloned() { + let auth_data = AuthData::Basic(basic.deref().clone()); + return self.inner.call((req, Some(auth_data))); + } + } + {{/isBasic}} + {{#isOAuth}} + { + use hyper::header::{Authorization, Basic, Bearer}; + use std::ops::Deref; + if let Some(bearer) = req.headers().get::>().cloned() { + let auth_data = AuthData::Bearer(bearer.deref().clone()); + return self.inner.call((req, Some(auth_data))); + } + } + {{/isOAuth}} + {{#isApiKey}} + {{#isKeyInHeader}} + { + header! { (ApiKey{{-index}}, "{{keyParamName}}") => [String] } + if let Some(header) = req.headers().get::().cloned() { + let auth_data = AuthData::ApiKey(header.0); + return self.inner.call((req, Some(auth_data))); + } + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + { + let key = form_urlencoded::parse(req.query().unwrap_or_default().as_bytes()) + .filter(|e| e.0 == "api_key_query") + .map(|e| e.1.clone().into_owned()) + .nth(0); + if let Some(key) = key { + let auth_data = AuthData::ApiKey(key); + return self.inner.call((req, Some(auth_data))); + } + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{/authMethods}} + + return self.inner.call((req, None)); + } +} diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-mod.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-mod.mustache new file mode 100644 index 000000000000..6b564f055469 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-server/server-mod.mustache @@ -0,0 +1,449 @@ +#![allow(unused_extern_crates)] +extern crate serde_ignored; +extern crate tokio_core; +extern crate native_tls; +extern crate hyper_tls; +extern crate openssl; +extern crate mime; +{{^apiUsesUuid}}extern crate uuid;{{/apiUsesUuid}} +extern crate chrono; +{{#apiHasFile}}extern crate multipart;{{/apiHasFile}} +extern crate percent_encoding; +extern crate url; + +{{#apiUsesUuid}}use uuid;{{/apiUsesUuid}} +use std::sync::Arc; +use futures::{Future, future, Stream, stream}; +use hyper; +use hyper::{Request, Response, Error, StatusCode}; +use hyper::header::{Headers, ContentType}; +use self::url::form_urlencoded; +use mimetypes; +{{#apiHasFile}}use self::multipart::server::Multipart; +use self::multipart::server::save::SaveResult;{{/apiHasFile}} + +use serde_json; +{{#usesXml}}use serde_xml_rs;{{/usesXml}} + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; +use std::io; + +#[allow(unused_imports)] +use std::collections::BTreeSet; + +pub use swagger::auth::Authorization; +use swagger::{ApiError, Context, XSpanId}; +use swagger::auth::Scopes; + +use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, + {{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + }; +#[allow(unused_imports)] +use models; + +pub mod auth; + +header! { (Warning, "Warning") => [String] } + +mod paths { + extern crate regex; + + lazy_static! { + pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(&[ +{{#pathSet}} + r"^{{basePathWithoutHost}}{{{pathRegEx}}}"{{^-last}},{{/-last}} +{{/pathSet}} + ]).unwrap(); + } +{{#pathSet}} + pub static ID_{{PATH_ID}}: usize = {{index}}; +{{#hasPathParams}} + lazy_static! { + pub static ref REGEX_{{PATH_ID}}: regex::Regex = regex::Regex::new(r"^{{basePathWithoutHost}}{{{pathRegEx}}}").unwrap(); + } +{{/hasPathParams}} +{{/pathSet}} +} + +pub struct NewService { + api_impl: Arc, +} + +impl NewService where T: Api + Clone + 'static { + pub fn new>>(api_impl: U) -> NewService { + NewService{api_impl: api_impl.into()} + } +} + +impl hyper::server::NewService for NewService where T: Api + Clone + 'static { + type Request = (Request, Context); + type Response = Response; + type Error = Error; + type Instance = Service; + + fn new_service(&self) -> Result { + Ok(Service::new(self.api_impl.clone())) + } +} + +pub struct Service { + api_impl: Arc, +} + +impl Service where T: Api + Clone + 'static { + pub fn new>>(api_impl: U) -> Service { + Service{api_impl: api_impl.into()} + } +} + +impl hyper::server::Service for Service where T: Api + Clone + 'static { + type Request = (Request, Context); + type Response = Response; + type Error = Error; + type Future = Box>; + + fn call(&self, (req, mut context): Self::Request) -> Self::Future { + let api_impl = self.api_impl.clone(); + let (method, uri, _, headers, body) = req.deconstruct(); + let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); + match &method { +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + // {{operationId}} - {{httpMethod}} {{path}} + &hyper::Method::{{vendorExtensions.HttpMethod}} if path.matched(paths::ID_{{vendorExtensions.PATH_ID}}) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } +{{#hasAuthMethods}} + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + {{#authMethods}} + {{#isOAuth}} + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + {{#scopes}} + "{{scope}}".to_string(), // {{description}} + {{/scopes}} + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body(missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + )) + )); + } + } + {{/isOAuth}} + {{/authMethods}} + } +{{/hasAuthMethods}} + +{{#vendorExtensions}}{{#hasPathParams}} + // Path parameters + let path = uri.path().to_string(); + let path_params = + paths::REGEX_{{PATH_ID}} + .captures(&path) + .unwrap_or_else(|| + panic!("Path {} matched RE {{PATH_ID}} in set but failed match against \"{}\"", path, paths::REGEX_{{PATH_ID}}.as_str()) + ); +{{/hasPathParams}}{{/vendorExtensions}} +{{#pathParams}} + let param_{{paramName}} = match percent_encoding::percent_decode(path_params["{{baseName}}"].as_bytes()).decode_utf8() { + Ok(param_{{paramName}}) => match param_{{paramName}}.parse::<{{{dataType}}}>() { + Ok(param_{{paramName}}) => param_{{paramName}}, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter {{baseName}}: {}", e)))), + }, + Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["{{baseName}}"])))) + }; +{{/pathParams}} +{{#headerParams}}{{#-first}} + // Header parameters +{{/-first}} + header! { (Request{{vendorExtensions.typeName}}, "{{baseName}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} } +{{#required}} + let param_{{paramName}} = match headers.get::() { + Some(param_{{paramName}}) => param_{{paramName}}.0.clone(), + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing or invalid required header {{baseName}}"))), + }; +{{/required}} +{{^required}} + let param_{{paramName}} = headers.get::().map(|header| header.0.clone()); +{{/required}}{{/headerParams}} + +{{#queryParams}}{{#-first}} + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); +{{/-first}} + let param_{{paramName}} = query_params.iter().filter(|e| e.0 == "{{baseName}}").map(|e| e.1.to_owned()) +{{#isListContainer}} + .filter_map(|param_{{paramName}}| param_{{paramName}}.parse::<{{{baseType}}}>().ok()) + .collect::>(); +{{^required}} + let param_{{paramName}} = if !param_{{paramName}}.is_empty() { + Some(param_{{paramName}}) + } else { + None + }; +{{/required}} +{{/isListContainer}}{{^isListContainer}} + .nth(0); +{{#required}} + let param_{{paramName}} = match param_{{paramName}} { + Some(param_{{paramName}}) => match param_{{paramName}}.parse::<{{{dataType}}}>() { + Ok(param_{{paramName}}) => param_{{paramName}}, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse query parameter {{baseName}} - doesn't match schema: {}", e)))), + }, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required query parameter {{baseName}}"))), + }; +{{/required}}{{^required}} + let param_{{paramName}} = param_{{paramName}}.and_then(|param_{{paramName}}| param_{{paramName}}.parse::<{{{baseType}}}>().ok()); +{{/required}} +{{/isListContainer}} +{{/queryParams}} + +{{#bodyParams}}{{#-first}} + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { +{{#vendorExtensions}}{{^consumesPlainText}} + let mut unused_elements = Vec::new(); +{{/consumesPlainText}} + let param_{{paramName}}: Option<{{{dataType}}}> = if !body.is_empty() { +{{#consumesXml}} + let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body); +{{/consumesXml}}{{#consumesJson}} + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); +{{/consumesJson}}{{^consumesPlainText}} + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_{{paramName}}) => param_{{paramName}}, +{{#required}} + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter {{baseName}} - doesn't match schema: {}", e)))), +{{/required}}{{^required}} + Err(_) => None, +{{/required}} + } +{{/consumesPlainText}}{{#consumesPlainText}} + match String::from_utf8(body.to_vec()) { + Ok(param_{{paramName}}) => Some(param_{{paramName}}), + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter {{baseName}} - not valid UTF-8: {}", e)))), + } +{{/consumesPlainText}}{{/vendorExtensions}} + } else { + None + }; +{{#required}} + let param_{{paramName}} = match param_{{paramName}} { + Some(param_{{paramName}}) => param_{{paramName}}, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter {{baseName}}"))), + }; +{{/required}} +{{/-first}}{{/bodyParams}} +{{^bodyParams}}{{#vendorExtensions}}{{#hasFile}} + let boundary = match multipart_boundary(&headers) { + Some(boundary) => boundary.to_string(), + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Couldn't find valid multipart body"))), + }; + + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + let mut entries = match Multipart::with_body(&body.to_vec()[..], boundary).save().temp() { + SaveResult::Full(entries) => { + entries + }, + _ => { + return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Unable to process all message parts")))) + }, + }; +{{#formParams}}{{#-first}} + // Form parameters +{{/-first}} + let param_{{paramName}} = entries.fields.remove("{{paramName}}"); + let param_{{paramName}} = match param_{{paramName}} { + Some(entry) => +{{#isFile}} + {{^required}}Some({{/required}}Box::new(stream::once(Ok(entry.as_bytes().to_vec()))) as Box, Error=io::Error> + Send>{{^required}}){{/required}}, +{{/isFile}}{{^isFile}} + match entry.parse::<{{{dataType}}}>() { + Ok(entry) => {{^required}}Some({{/required}}entry{{^required}}){{/required}}, +{{#required}} + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse form parameter {{baseName}} - doesn't match schema: {}", e)))), +{{/required}}{{^required}} + Err(_) => None, +{{/required}} + }, +{{/isFile}} +{{#required}} + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Missing required form parameter {{paramName}}")))), +{{/required}}{{^required}} + None => None, +{{/required}} + }; +{{^required}}{{#isFile}} let param_{{paramName}} = Box::new(future::ok(param_{{paramName}}));{{/isFile}}{{/required}} +{{/formParams}} +{{/hasFile}}{{^hasFile}} + Box::new(({ + {{ +{{#formParams}}{{#-first}} + // Form parameters +{{/-first}} + let param_{{paramName}} = {{^isContainer}}{{#vendorExtensions}}{{{example}}};{{/vendorExtensions}}{{/isContainer}}{{#isListContainer}}{{#required}}Vec::new();{{/required}}{{^required}}None;{{/required}}{{/isListContainer}}{{#isMapContainer}}None;{{/isMapContainer}} +{{/formParams}} +{{/hasFile}}{{/vendorExtensions}}{{/bodyParams}} + Box::new(api_impl.{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}param_{{paramName}}{{#isListContainer}}.as_ref(){{/isListContainer}}, {{/allParams}}&context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); +{{#bodyParams}}{{#vendorExtensions}}{{^consumesPlainText}} + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } +{{/consumesPlainText}}{{/vendorExtensions}}{{/bodyParams}} + match result { + Ok(rsp) => match rsp { +{{#responses}} + {{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}} +{{#dataType}}{{^headers}} + (body) +{{/headers}}{{#headers}} +{{#-first}} + { + body, +{{/-first}} + {{name}}{{^-last}}, {{/-last}} +{{#-last}} + } +{{/-last}} +{{/headers}}{{/dataType}} +{{^dataType}}{{#headers}}{{#-first}} + { +{{/-first}} + {{name}}{{^-last}}, {{/-last}} +{{#-last}} + } +{{/-last}} +{{/headers}}{{/dataType}} + => { +{{^isFile}} response.set_status(StatusCode::try_from({{code}}).unwrap()); +{{#headers}} + header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{datatype}}}] } + response.headers_mut().set(Response{{nameInCamelCase}}({{name}})); +{{/headers}} +{{#produces}}{{#-first}}{{#dataType}} + response.headers_mut().set(ContentType(mimetypes::responses::{{#vendorExtensions}}{{uppercase_operation_id}}_{{x-uppercaseResponseId}}{{/vendorExtensions}}.clone())); +{{/dataType}}{{/-first}}{{/produces}} +{{#dataType}} +{{#vendorExtensions}}{{#producesXml}}{{^has_namespace}} + let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); +{{/has_namespace}}{{#has_namespace}} + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); + let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); +{{/has_namespace}}{{/producesXml}}{{#producesJson}} + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); +{{/producesJson}}{{/vendorExtensions}} + response.set_body(body); +{{/dataType}}{{/isFile}}{{#isFile}} + let body = body.fold(Vec::new(), | mut body, chunk| { + body.extend(chunk.iter()); + future::ok::, io::Error>(body) + }) + // Block whilst waiting for the stream to complete + .wait(); + + match body { + // If no error occurred then create successful hyper response + Ok(vec) => { + response.set_status(StatusCode::try_from({{code}}).unwrap()); + +{{#headers}} + header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{datatype}}}] } + response.headers_mut().set(Response{{nameInCamelCase}}({{name}})); +{{/headers}}{{#produces}}{{#-first}}{{#dataType}} + response.headers_mut().set(ContentType(mimetypes::responses::{{#vendorExtensions}}{{uppercase_operation_id}}_{{x-uppercaseResponseId}}{{/vendorExtensions}}.clone())); +{{/dataType}}{{/-first}}{{/produces}} + response.set_body(vec); + }, + // It's possible that errors were received in the stream, if this is the case then we can't return a success response to the client and instead must return an internal error. + Err(e) => { + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + } + } +{{/isFile}} + }, +{{/responses}} + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) +{{^bodyParams}}{{#vendorExtensions}}{{^hasFile}} + }} + })) as Box> +{{/hasFile}}{{#hasFile}} + as Box> + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read multipart body")))), + } + }) + ) +{{/hasFile}}{{/vendorExtensions}}{{/bodyParams}} +{{#bodyParams}}{{#-first}} + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter {{baseName}}: {}", e)))), + } + }) + ) as Box> +{{/-first}}{{/bodyParams}} + }, + +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + _ => Box::new(future::ok(Response::new().with_status(StatusCode::NotFound))) as Box>, + } + } +} + +{{#apiHasFile}} +/// Utility function to get the multipart boundary marker (if any) from the Headers. +fn multipart_boundary<'a>(headers: &'a Headers) -> Option<&'a str> { + headers.get::().and_then(|content_type| { + let ContentType(ref mime) = *content_type; + if mime.type_() == mime::MULTIPART && mime.subtype() == mime::FORM_DATA { + mime.get_param(mime::BOUNDARY).map(|x| x.as_str()) + } else { + None + } + }) +} +{{/apiHasFile}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/server.mustache b/modules/openapi-generator/src/main/resources/rust-server/server.mustache deleted file mode 100644 index edce03389f7a..000000000000 --- a/modules/openapi-generator/src/main/resources/rust-server/server.mustache +++ /dev/null @@ -1,340 +0,0 @@ -#![allow(unused_extern_crates)] -extern crate serde_ignored; -extern crate iron; -extern crate router; -extern crate bodyparser; -extern crate urlencoded; -extern crate uuid; -extern crate chrono; -{{#apiHasFile}}extern crate multipart;{{/apiHasFile}} - -use futures::Future; -use futures::future; -use futures::{stream, Stream}; -use hyper; -use hyper::header::{Headers, ContentType}; -use self::iron::prelude::*; -use self::iron::{status, modifiers, BeforeMiddleware}; -use self::iron::url::percent_encoding::percent_decode; -use self::router::Router; -use self::urlencoded::UrlEncodedQuery; -use mimetypes; -{{#apiHasFile}}use multipart::server::{Multipart, SaveResult};{{/apiHasFile}} - -use serde_json; -{{#usesXml}}use serde_xml_rs;{{/usesXml}} - -#[allow(unused_imports)] -use std::collections::{HashMap, BTreeMap}; -#[allow(unused_imports)] -use swagger; -use std::io::Error; - -#[allow(unused_imports)] -use std::collections::BTreeSet; - -pub use swagger::auth::Authorization; -use swagger::auth::{AuthData, Scopes}; -use swagger::{ApiError, Context, XSpanId}; - -use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, - {{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} - }; -#[allow(unused_imports)] -use models; - -header! { (Warning, "Warning") => [String] } - -/// Create a new router for `Api` -pub fn router(api: T) -> Router where T: Api + Send + Sync + Clone + 'static { - let mut router = Router::new(); - add_routes(&mut router, api); - router -} - -/// Add routes for `Api` to a provided router. -/// -/// Note that these routes are added straight onto the router. This means that if the router -/// already has a route for an endpoint which clashes with those provided by this API, then the -/// old route will be lost. -/// -/// It is generally a bad idea to add routes in this way to an existing router, which may have -/// routes on it for other APIs. Distinct APIs should be behind distinct paths to encourage -/// separation of interfaces, which this function does not enforce. APIs should not overlap. -/// -/// Alternative approaches include: -/// -/// - generate an `iron::middleware::Handler` (usually a `router::Router` or -/// `iron::middleware::chain`) for each interface, and add those handlers inside an existing -/// router, mounted at different paths - so the interfaces are separated by path -/// - use a different instance of `iron::Iron` for each interface - so the interfaces are -/// separated by the address/port they listen on -/// -/// This function exists to allow legacy code, which doesn't separate its APIs properly, to make -/// use of this crate. -#[deprecated(note="APIs should not overlap - only for use in legacy code.")] -pub fn route(router: &mut Router, api: T) where T: Api + Send + Sync + Clone + 'static { - add_routes(router, api) -} - -/// Add routes for `Api` to a provided router -fn add_routes(router: &mut Router, api: T) where T: Api + Send + Sync + Clone + 'static { -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} - let api_clone = api.clone(); - router.{{#vendorExtensions}}{{httpmethod}}{{/vendorExtensions}}( - "{{#vendorExtensions}}{{basePathWithoutHost}}{{path}}{{/vendorExtensions}}", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - {{#hasAuthMethods}} - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - {{#authMethods}} - {{#isOAuth}} - // Authorization - if let Scopes::Some(ref scopes) = authorization.scopes { - let required_scopes: BTreeSet = vec![ - {{#scopes}} - "{{scope}}".to_string(), // {{description}} - {{/scopes}} - ].into_iter().collect(); - - if !required_scopes.is_subset(scopes) { - let missing_scopes = required_scopes.difference(scopes); - return Err(Response::with(( - status::Forbidden, - missing_scopes.fold( - "Insufficient authorization, missing scopes".to_string(), - |s, scope| format!("{} {}", s, scope) - ) - ))); - } - } - {{/isOAuth}} - {{/authMethods}} - {{/hasAuthMethods}} - -{{#pathParams}}{{#-first}} - // Path parameters -{{/-first}} let param_{{paramName}} = { - let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? - .find("{{baseName}}").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter {{baseName}}".to_string())))?; - percent_decode(param.as_bytes()).decode_utf8() - .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? - .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter {{baseName}}: {}", e))))? - }; -{{/pathParams}} -{{#headerParams}}{{#-first}} - // Header parameters -{{/-first}} header! { (Request{{vendorExtensions.typeName}}, "{{baseName}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} } -{{#required}} let param_{{paramName}} = req.headers.get::().ok_or_else(|| Response::with((status::BadRequest, "Missing or invalid required header {{baseName}}".to_string())))?.0.clone(); -{{/required}}{{^required}} let param_{{paramName}} = req.headers.get::().map(|header| header.0.clone()); -{{/required}}{{/headerParams}} -{{#queryParams}}{{#-first}} - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = req.get::().unwrap_or_default(); -{{/-first}} let param_{{paramName}} = query_params.get("{{baseName}}") -{{#required}} .ok_or_else(|| Response::with((status::BadRequest, "Missing required query parameter {{baseName}}".to_string())))? -{{#isListContainer}} .iter().flat_map(|x| x.parse::<{{{baseType}}}>()).collect::>(); -{{/isListContainer}}{{^isListContainer}} .first().ok_or_else(|| Response::with((status::BadRequest, "Required query parameter {{baseName}} was empty".to_string())))? - .parse::<{{{dataType}}}>().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse query parameter {{baseName}} - doesn't match schema: {}", e))))?; -{{/isListContainer}}{{/required}}{{^required}}{{#isListContainer}} .map(|list| list.iter().flat_map(|x| x.parse::<{{{baseType}}}>()).collect::>()); -{{/isListContainer}}{{^isListContainer}} .and_then(|list| list.first()).and_then(|x| x.parse::<{{{dataType}}}>().ok()); -{{/isListContainer}}{{/required}}{{/queryParams}} -{{#bodyParams}}{{#-first}} // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. -{{/-first}}{{#required}} - let param_{{paramName}} = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter {{baseName}} - not valid UTF-8: {}", e))))?; -{{/required}}{{^required}} - let param_{{paramName}} = req.get::().unwrap_or(None); -{{/required}}{{#vendorExtensions}}{{^consumesPlainText}} - let mut unused_elements = Vec::new(); - - let param_{{paramName}} = if let Some(param_{{paramName}}_raw) = param_{{paramName}} { {{#consumesXml}} - let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(param_{{paramName}}_raw.as_bytes());{{/consumesXml}}{{#consumesJson}} - let deserializer = &mut serde_json::Deserializer::from_str(¶m_{{paramName}}_raw);{{/consumesJson}} - - let param_{{paramName}}: Option<{{{dataType}}}> = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }){{#required}}.map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter {{baseName}} - doesn't match schema: {}", e))))?{{/required}}{{^required}}.unwrap_or(None){{/required}}; - - param_{{paramName}} - } else { - None - };{{/consumesPlainText}}{{/vendorExtensions}}{{#required}} - let param_{{paramName}} = param_{{paramName}}.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter {{baseName}}".to_string())))?{{/required}}; - -{{/bodyParams}} -{{#formParams}} - {{#-first}} - // Form parameters -{{/-first}}{{/formParams}}{{#vendorExtensions}}{{#hasFile}} - // Expecting a multipart form, extract and parse it now. - let mut entries = match Multipart::from_request(req) { - Ok(mut multipart) => { - - match multipart.save().temp() { - SaveResult::Full(entries) => { - Ok(entries) - }, - _ => { - Err(Response::with((status::InternalServerError, format!("Unable to process all message parts")))) - }, - } - }, - Err(e) => { - // Unable to parse as multipart - Err(Response::with((status::BadRequest, format!("Couldn't parse body as multipart")))) - } - }?; - -{{/hasFile}}{{/vendorExtensions}}{{#allParams}}{{#isFormParam}}{{#isFile}} - - let param_{{paramName}} = entries.fields.remove("{{paramName}}"); - - let param_{{paramName}} = match param_{{paramName}} { - Some(body) => { - Ok({let bytes = body.as_bytes(); - {{^required}}Some({{/required}} - Box::new(stream::once(Ok(bytes.to_vec()))) as Box, Error=Error> + Send> - {{^required}}){{/required}}} - ) - } - None => {Err(Response::with((status::BadRequest, format!("Body part not found!"))))} - }?; -{{/isFile}} - let param_{{paramName}} = {{#isFile}}{{^required}}Box::new(future::ok({{/required}}param_{{paramName}}{{^required}})){{/required}};{{/isFile}}{{^isFile}}{{^isContainer}}{{#vendorExtensions}}{{{example}}};{{/vendorExtensions}}{{/isContainer}}{{#isListContainer}}{{#required}}Vec::new();{{/required}}{{^required}}None;{{/required}}{{/isListContainer}}{{#isMapContainer}}None;{{/isMapContainer}}{{/isFile}} - {{/isFormParam}} -{{/allParams}} - - match api.{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}param_{{paramName}}{{#isListContainer}}.as_ref(){{/isListContainer}}, {{/allParams}}context).wait() { - Ok(rsp) => match rsp { -{{#responses}} - {{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}{{#dataType}}{{^headers}}(body){{/headers}}{{#headers}}{{#-first}}{ body{{/-first}}{{/headers}}{{/dataType}}{{#headers}}{{#-first}}{{^dataType}}{ {{/dataType}}{{#dataType}}, {{/dataType}}{{/-first}}{{^-first}}, {{/-first}}{{name}}{{#-last}} }{{/-last}}{{/headers}} => { -{{^isFile}} -{{#dataType}}{{#vendorExtensions}}{{#producesPlainText}} let body_string = body; -{{/producesPlainText}}{{#producesXml}} -{{^has_namespace}} let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize");{{/has_namespace}}{{#has_namespace}} - let mut namespaces = BTreeMap::new(); - // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); - let body_string = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize");{{/has_namespace}}{{/producesXml}}{{#producesJson}} - let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize");{{/producesJson}}{{/vendorExtensions}}{{/dataType}} - - let mut response = Response::with((status::Status::from_u16({{code}}){{#dataType}}, body_string{{/dataType}}));{{/isFile}}{{#isFile}} body.fold(Vec::new(), |mut body, chunk| { - body.extend(chunk.iter()); - future::ok::, Error>(body) - }) - - // Block whilst waiting for the stream to complete - .wait() - - // It's possible that errors were received in the stream, if this is the case then we can't return a success response to the client and instead must return an internal error. - .map_err(|_| Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - - // Assuming no errors then create an Iron response. - .map(|rsp| { - let mut response = Response::new(); - response.status = Some(status::Status::from_u16({{code}})); - response.body = Some(Box::new(rsp)); -{{/isFile}} -{{#headers}}{{#isFile}} {{/isFile}} header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{datatype}}}] } -{{#isFile}} {{/isFile}} response.headers.set(Response{{nameInCamelCase}}({{name}})); -{{/headers}} - {{#produces}}{{#-first}} -{{#dataType}}{{#isFile}} {{/isFile}} response.headers.set(ContentType(mimetypes::responses::{{#vendorExtensions}}{{uppercase_operation_id}}_{{x-uppercaseResponseId}}{{/vendorExtensions}}.clone()));{{/dataType}} -{{/-first}}{{/produces}} -{{#isFile}} {{/isFile}} context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); -{{#bodyParams}}{{#vendorExtensions}}{{^consumesPlainText}} if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - }{{/consumesPlainText}}{{/vendorExtensions}}{{/bodyParams}} - {{^isFile}}Ok(response){{/isFile}}{{#isFile}} response - }){{/isFile}} - }, -{{/responses}} - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "{{operationId}}"); -{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} -} - -/// Middleware to extract authentication data from request -pub struct ExtractAuthData; - -impl BeforeMiddleware for ExtractAuthData { - fn before(&self, req: &mut Request) -> IronResult<()> { - {{#authMethods}} - {{#isBasic}} - { - use hyper::header::{Authorization, Basic, Bearer}; - use std::ops::Deref; - if let Some(basic) = req.headers.get::>() { - req.extensions.insert::(AuthData::Basic(basic.deref().clone())); - return Ok(()); - } - } - {{/isBasic}} - {{#isOAuth}} - { - use hyper::header::{Authorization, Basic, Bearer}; - use std::ops::Deref; - if let Some(bearer) = req.headers.get::>() { - req.extensions.insert::(AuthData::Bearer(bearer.deref().clone())); - return Ok(()); - } - } - {{/isOAuth}} - {{#isApiKey}} - {{#isKeyInHeader}} - { - header! { (ApiKey{{-index}}, "{{keyParamName}}") => [String] } - if let Some(header) = req.headers.get::() { - req.extensions.insert::(AuthData::ApiKey(header.0.clone())); - return Ok(()); - } - } - {{/isKeyInHeader}} - {{#isKeyInQuery}} - { - let header = match req.get_ref::() { - Ok(query) => query.get("{{keyParamName}}").map(|v| v[0].clone()), - _ => None - }; - if let Some(key) = header { - req.extensions.insert::(AuthData::ApiKey(key)); - return Ok(()); - } - } - {{/isKeyInQuery}} - {{/isApiKey}} - {{/authMethods}} - - Ok(()) - } -} diff --git a/modules/openapi-generator/src/main/resources/rust/api.mustache b/modules/openapi-generator/src/main/resources/rust/api.mustache index 21c45ef38dbc..55604ca79332 100644 --- a/modules/openapi-generator/src/main/resources/rust/api.mustache +++ b/modules/openapi-generator/src/main/resources/rust/api.mustache @@ -2,6 +2,7 @@ use std::rc::Rc; use std::borrow::Borrow; use std::borrow::Cow; +use std::collections::HashMap; use hyper; use serde_json; @@ -39,26 +40,71 @@ impl{{classname}} for {{classname}}Client { fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>> { let configuration: &configuration::Configuration = self.configuration.borrow(); +{{#hasAuthMethods}} + let mut auth_headers = HashMap::::new(); + let mut auth_query = HashMap::::new(); +{{#authMethods}} +{{#isApiKey}} + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let val = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + {{#isKeyInHeader}} + auth_headers.insert("{{keyParamName}}".to_owned(), val); + {{/isKeyInHeader}} + {{#isKeyInQuery}} + auth_query.insert("{{keyParamName}}".to_owned(), val); + {{/isKeyInQuery}} + }; +{{/isApiKey}} +{{#isBasic}} + if let Some(ref auth_conf) = configuration.basic_auth { + let auth = hyper::header::Authorization( + hyper::header::Basic { + username: auth_conf.0.to_owned(), + password: auth_conf.1.to_owned(), + } + ); + auth_headers.insert("Authorization".to_owned(), auth.to_string()); + }; +{{/isBasic}} +{{#isOAuth}} + if let Some(ref token) = configuration.oauth_access_token { + let auth = hyper::header::Authorization( + hyper::header::Bearer { + token: token.to_owned(), + } + ); + auth_headers.insert("Authorization".to_owned(), auth.to_string()); + }; +{{/isOAuth}} +{{/authMethods}} +{{/hasAuthMethods}} let method = hyper::Method::{{httpMethod}}; - {{^hasQueryParams}} - let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}}); - {{/hasQueryParams}} - {{#hasQueryParams}} - let query = ::url::form_urlencoded::Serializer::new(String::new()) - {{#queryParams}} - .append_pair("{{baseName}}", &{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()) - {{/queryParams}} - .finish(); - let uri_str = format!("{}{{{path}}}{}", configuration.base_path, query{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}}); - {{/hasQueryParams}} - - let uri = uri_str.parse(); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); +{{#queryParams}} + query.append_pair("{{baseName}}", &{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); +{{/queryParams}} +{{#hasAuthMethods}} + for (key, val) in &auth_query { + query.append_pair(key, val); + } +{{/hasAuthMethods}} + query.finish() + }; + let uri_str = format!("{}{{{path}}}?{}", configuration.base_path, query_string{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}}); + // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); @@ -73,6 +119,12 @@ impl{{classname}} for {{classname}}Client { } {{/hasHeaderParams}} + {{#hasAuthMethods}} + for (key, val) in auth_headers { + req.headers_mut().set_raw(key, val); + } + {{/hasAuthMethods}} + {{#hasBodyParam}} {{#bodyParams}} let serialized = serde_json::to_string(&{{paramName}}).unwrap(); diff --git a/modules/openapi-generator/src/main/resources/rust/configuration.mustache b/modules/openapi-generator/src/main/resources/rust/configuration.mustache index c555c6658605..ff2d673b27c5 100644 --- a/modules/openapi-generator/src/main/resources/rust/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/rust/configuration.mustache @@ -1,10 +1,22 @@ {{>partial_header}} use hyper; +use std::collections::HashMap; pub struct Configuration { pub base_path: String, pub user_agent: Option, pub client: hyper::client::Client, + pub basic_auth: Option, + pub oauth_access_token: Option, + pub api_key: Option, + // TODO: take an oauth2 token source, similar to the go one +} + +pub type BasicAuth = (String, Option); + +pub struct ApiKey { + pub prefix: Option, + pub key: String, } impl Configuration { @@ -13,6 +25,9 @@ impl Configuration { base_path: "{{{basePath}}}".to_owned(), user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("Swagger-Codegen/{{version}}/rust".to_owned()){{/httpUserAgent}}, client: client, + basic_auth: None, + oauth_access_token: None, + api_key: None, } } } diff --git a/modules/openapi-generator/src/main/resources/sinatra/api.mustache b/modules/openapi-generator/src/main/resources/sinatra/api.mustache index 89574ac317f0..5587837fbdf6 100644 --- a/modules/openapi-generator/src/main/resources/sinatra/api.mustache +++ b/modules/openapi-generator/src/main/resources/sinatra/api.mustache @@ -16,10 +16,16 @@ MyApp.add_route('{{httpMethod}}', '{{{basePathWithoutHost}}}{{{path}}}', { "name" => "{{paramName}}", "description" => "{{description}}", "dataType" => "{{dataType}}", + {{#collectionFormat}} + "collectionFormat" => "{{collectionFormat}}", + {{/collectionFormat}} + {{^isContainer}} + "allowableValues" => "{{{allowableValues.values}}}", + {{/isContainer}} + {{#defaultValue}} + "defaultValue" => "{{{defaultValue}}}", + {{/defaultValue}} "paramType" => "query", - {{#collectionFormat}}"collectionFormat" => "{{collectionFormat}}",{{/collectionFormat}} - "allowableValues" => "{{^isContainer}}{{{allowableValues.values}}}{{/isContainer}}", - {{#defaultValue}}"defaultValue" => "{{{defaultValue}}}"{{/defaultValue}} }, {{/queryParams}} {{#pathParams}} diff --git a/modules/openapi-generator/src/main/resources/sinatra/openapi.mustache b/modules/openapi-generator/src/main/resources/sinatra/openapi.mustache new file mode 100644 index 000000000000..51ebafb0187d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/sinatra/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/sinatra/swagger.mustache b/modules/openapi-generator/src/main/resources/sinatra/swagger.mustache deleted file mode 100644 index 51560926bba1..000000000000 --- a/modules/openapi-generator/src/main/resources/sinatra/swagger.mustache +++ /dev/null @@ -1 +0,0 @@ -{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swagger/README.md b/modules/openapi-generator/src/main/resources/swagger/README.md deleted file mode 100644 index 0c2b69a24dbd..000000000000 --- a/modules/openapi-generator/src/main/resources/swagger/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# Swagger JSON -This is a swagger JSON built by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift/api.mustache b/modules/openapi-generator/src/main/resources/swift/api.mustache index 77debc916523..763269f13424 100644 --- a/modules/openapi-generator/src/main/resources/swift/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift/api.mustache @@ -93,15 +93,25 @@ public class {{classname}}: APIBase { - {{httpMethod}} {{{path}}}{{#notes}} - {{{notes}}}{{/notes}}{{#subresourceOperation}} - subresourceOperation: {{subresourceOperation}}{{/subresourceOperation}}{{#defaultResponse}} - - defaultResponse: {{defaultResponse}}{{/defaultResponse}}{{#authMethods}} + - defaultResponse: {{defaultResponse}} + {{/defaultResponse}} + {{#authMethods}} - {{#isBasic}}BASIC{{/isBasic}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}: - type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeaer}}(HEADER){{/isKeyInHeaer}}{{/keyParamName}} - - name: {{name}}{{/authMethods}}{{#responseHeaders}} - - responseHeaders: {{responseHeaders}}{{/responseHeaders}}{{#examples}} - - examples: {{{examples}}}{{/examples}}{{#externalDocs}} - - externalDocs: {{externalDocs}}{{/externalDocs}}{{#hasParams}} - {{/hasParams}}{{#allParams}} - - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + - name: {{name}} + {{/authMethods}} + {{#hasResponseHeaders}} + - responseHeaders: [{{#responseHeaders}}{{{baseName}}}({{{datatype}}}){{^-last}}, {{/-last}}{{/responseHeaders}}] + {{/hasResponseHeaders}} + {{#examples}} + - examples: {{{examples}}} + {{/examples}} + {{#externalDocs}} + - externalDocs: {{externalDocs}} + {{/externalDocs}} + {{#allParams}} + - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} + {{/allParams}} - returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}} */ diff --git a/modules/openapi-generator/src/main/resources/swift3/APIHelper.mustache b/modules/openapi-generator/src/main/resources/swift3/APIHelper.mustache index f5a6b4779524..4b90cfc5b4e0 100644 --- a/modules/openapi-generator/src/main/resources/swift3/APIHelper.mustache +++ b/modules/openapi-generator/src/main/resources/swift3/APIHelper.mustache @@ -68,7 +68,7 @@ class APIHelper { } } .flatMap { $0 } - + if returnValues.isEmpty { return nil } return returnValues } diff --git a/modules/openapi-generator/src/main/resources/swift3/AlamofireImplementations.mustache b/modules/openapi-generator/src/main/resources/swift3/AlamofireImplementations.mustache index 2b001505c235..863f618326d3 100644 --- a/modules/openapi-generator/src/main/resources/swift3/AlamofireImplementations.mustache +++ b/modules/openapi-generator/src/main/resources/swift3/AlamofireImplementations.mustache @@ -345,7 +345,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } @@ -373,4 +373,4 @@ fileprivate enum DownloadException : Error { case requestMissing case requestMissingPath case requestMissingURL -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/resources/swift3/Configuration.mustache b/modules/openapi-generator/src/main/resources/swift3/Configuration.mustache index c03a10b930c5..7f777932fe96 100644 --- a/modules/openapi-generator/src/main/resources/swift3/Configuration.mustache +++ b/modules/openapi-generator/src/main/resources/swift3/Configuration.mustache @@ -7,9 +7,9 @@ import Foundation open class Configuration { - - // This value is used to configure the date formatter that is used to serialize dates into JSON format. - // You must set it prior to encoding any dates, and it will only be read once. + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/modules/openapi-generator/src/main/resources/swift3/Models.mustache b/modules/openapi-generator/src/main/resources/swift3/Models.mustache index 11a6f4fb0f1c..f39de3dce814 100644 --- a/modules/openapi-generator/src/main/resources/swift3/Models.mustache +++ b/modules/openapi-generator/src/main/resources/swift3/Models.mustache @@ -199,7 +199,7 @@ class Decoders { return .success(nil) } } - + static func decodeOptional(clazz: [T].Type, source: AnyObject?) -> Decoded<[T]?> where T: RawRepresentable { if let source = source as? [AnyObject] { var values = [T]() @@ -304,7 +304,7 @@ class Decoders { {{#models}} {{#model}} - {{^isArrayModel}} + {{^isArrayModel}} // Decoder for [{{{classname}}}] Decoders.addDecoder(clazz: [{{{classname}}}].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[{{{classname}}}]> in return Decoders.decode(clazz: [{{{classname}}}].self, source: source) diff --git a/modules/openapi-generator/src/main/resources/swift3/api.mustache b/modules/openapi-generator/src/main/resources/swift3/api.mustache index f32b668c64ff..074f96f432f8 100644 --- a/modules/openapi-generator/src/main/resources/swift3/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift3/api.mustache @@ -109,10 +109,17 @@ open class {{classname}}: APIBase { {{#authMethods}} - {{#isBasic}}BASIC{{/isBasic}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}: - type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeaer}}(HEADER){{/isKeyInHeaer}}{{/keyParamName}} - - name: {{name}}{{/authMethods}}{{#responseHeaders}} - - responseHeaders: {{responseHeaders}}{{/responseHeaders}}{{#examples}} - - examples: {{{examples}}}{{/examples}}{{#externalDocs}} - - externalDocs: {{externalDocs}}{{/externalDocs}} + - name: {{name}} + {{/authMethods}} + {{#hasResponseHeaders}} + - responseHeaders: [{{#responseHeaders}}{{{baseName}}}({{{datatype}}}){{^-last}}, {{/-last}}{{/responseHeaders}}] + {{/hasResponseHeaders}} + {{#examples}} + - examples: {{{examples}}} + {{/examples}} + {{#externalDocs}} + - externalDocs: {{externalDocs}} + {{/externalDocs}} {{#allParams}} - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} @@ -141,16 +148,14 @@ open class {{classname}}: APIBase { {{^hasFormParams}} let parameters: [String:Any]? = nil {{/hasFormParams}} - {{/bodyParam}} - - let url = NSURLComponents(string: URLString) - {{#hasQueryParams}} + {{/bodyParam}}{{#hasQueryParams}} + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ {{#queryParams}} - {{> _param}}{{#hasMore}}, {{/hasMore}} + {{> _param}}{{#hasMore}},{{/hasMore}} {{/queryParams}} - ]) - {{/hasQueryParams}} + ]){{/hasQueryParams}}{{^hasQueryParams}} + let url = URLComponents(string: URLString){{/hasQueryParams}} {{#headerParams}} {{^secondaryParam}} let nillableHeaders: [String: Any?] = [ diff --git a/modules/openapi-generator/src/main/resources/swift3/git_push.sh.mustache b/modules/openapi-generator/src/main/resources/swift3/git_push.sh.mustache index a2d752348373..f65b794638f7 100755 --- a/modules/openapi-generator/src/main/resources/swift3/git_push.sh.mustache +++ b/modules/openapi-generator/src/main/resources/swift3/git_push.sh.mustache @@ -28,7 +28,7 @@ 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. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote diff --git a/modules/openapi-generator/src/main/resources/swift3/gitignore.mustache b/modules/openapi-generator/src/main/resources/swift3/gitignore.mustache index 5e5d5cebcf47..fc4e330f8fab 100644 --- a/modules/openapi-generator/src/main/resources/swift3/gitignore.mustache +++ b/modules/openapi-generator/src/main/resources/swift3/gitignore.mustache @@ -54,7 +54,7 @@ Carthage/Build # fastlane # -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md diff --git a/modules/openapi-generator/src/main/resources/swift4/APIHelper.mustache b/modules/openapi-generator/src/main/resources/swift4/APIHelper.mustache index b612ff90921a..81e7286d6d40 100644 --- a/modules/openapi-generator/src/main/resources/swift4/APIHelper.mustache +++ b/modules/openapi-generator/src/main/resources/swift4/APIHelper.mustache @@ -6,12 +6,11 @@ import Foundation -class APIHelper { - static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { - var destination = [String:Any]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = value +public struct APIHelper { + public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + let destination = source.reduce(into: [String: Any]()) { (result, item) in + if let value = item.value { + result[item.key] = value } } @@ -21,45 +20,46 @@ class APIHelper { return destination } - static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { - var destination = [String:String]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = "\(value)" + public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + return source.reduce(into: [String: String]()) { (result, item) in + if let collection = item.value as? Array { + result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = "\(value)" } } - return destination } - static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { guard let source = source else { return nil } - var destination = [String:Any]() - let theTrue = NSNumber(value: true as Bool) - let theFalse = NSNumber(value: false as Bool) - for (key, value) in source { - switch value { - case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse: - destination[key] = "\(value as! Bool)" as Any? + + return source.reduce(into: [String: Any](), { (result, item) in + switch item.value { + case let x as Bool: + result[item.key] = x.description default: - destination[key] = value + result[item.key] = item.value } - } - return destination + }) } - static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { - let returnValues = values - .filter { $0.1 != nil } - .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in - URLQueryItem(name: item._key, value:"\(item._value!)") + public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in + if let collection = item.value as? Array { + let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + result.append(URLQueryItem(name: item.key, value: value)) + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: "\(value)")) } - if returnValues.count == 0 { + } + + if destination.isEmpty { return nil } - return returnValues + return destination } - } + diff --git a/modules/openapi-generator/src/main/resources/swift4/AlamofireImplementations.mustache b/modules/openapi-generator/src/main/resources/swift4/AlamofireImplementations.mustache index 24351523736d..381fddcc81fb 100644 --- a/modules/openapi-generator/src/main/resources/swift4/AlamofireImplementations.mustache +++ b/modules/openapi-generator/src/main/resources/swift4/AlamofireImplementations.mustache @@ -268,7 +268,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } diff --git a/modules/openapi-generator/src/main/resources/swift4/JSONEncodingHelper.mustache b/modules/openapi-generator/src/main/resources/swift4/JSONEncodingHelper.mustache index 4cf4ac206af5..19ee06b1f487 100644 --- a/modules/openapi-generator/src/main/resources/swift4/JSONEncodingHelper.mustache +++ b/modules/openapi-generator/src/main/resources/swift4/JSONEncodingHelper.mustache @@ -24,4 +24,20 @@ open class JSONEncodingHelper { return params } + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { + var params: Parameters? = nil + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error) + return nil + } + } + + return params + } + } diff --git a/modules/openapi-generator/src/main/resources/swift4/api.mustache b/modules/openapi-generator/src/main/resources/swift4/api.mustache index fcb9ddff8cda..5f5b0d4ebc13 100644 --- a/modules/openapi-generator/src/main/resources/swift4/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift4/api.mustache @@ -36,9 +36,18 @@ open class {{classname}} { - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - parameter completion: completion handler to receive the data and the error objects */ - open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: @escaping ((_ {{#returnType}}data: {{{returnType}}}?,_ {{/returnType}}error: Error?) -> Void)) { + open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: @escaping ((_ data: {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}?,_ error: Error?) -> Void)) { {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute { (response, error) -> Void in - completion({{#returnType}}response?.body, {{/returnType}}error); + {{#returnType}} + completion(response?.body, error) + {{/returnType}} + {{^returnType}} + if error == nil { + completion((), error) + } else { + completion(nil, error) + } + {{/returnType}} } } @@ -52,11 +61,11 @@ open class {{classname}} { */ open class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { let deferred = Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.pending() - {{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#returnType}}data, {{/returnType}}error in + {{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill({{#returnType}}data!{{/returnType}}) + deferred.fulfill(data!) } } return deferred.promise @@ -72,11 +81,11 @@ open class {{classname}} { */ open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { return Observable.create { observer -> Disposable in - {{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#returnType}}data, {{/returnType}}error in + {{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next({{#returnType}}data!{{/returnType}}{{^returnType}}(){{/returnType}})) + observer.on(.next(data!)) } observer.on(.completed) } @@ -92,16 +101,24 @@ open class {{classname}} { - {{httpMethod}} {{{path}}}{{#notes}} - {{{notes}}}{{/notes}}{{#subresourceOperation}} - subresourceOperation: {{subresourceOperation}}{{/subresourceOperation}}{{#defaultResponse}} - - defaultResponse: {{defaultResponse}}{{/defaultResponse}}{{#authMethods}} + - defaultResponse: {{defaultResponse}}{{/defaultResponse}} + {{#authMethods}} - {{#isBasic}}BASIC{{/isBasic}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}: - type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeaer}}(HEADER){{/isKeyInHeaer}}{{/keyParamName}} - - name: {{name}}{{/authMethods}}{{#responseHeaders}} - - responseHeaders: {{responseHeaders}}{{/responseHeaders}}{{#examples}} - - examples: {{{examples}}}{{/examples}}{{#externalDocs}} - - externalDocs: {{externalDocs}}{{/externalDocs}}{{#hasParams}} - {{/hasParams}}{{#allParams}} - - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - + - name: {{name}} + {{/authMethods}} + {{#hasResponseHeaders}} + - responseHeaders: [{{#responseHeaders}}{{{baseName}}}({{{datatype}}}){{^-last}}, {{/-last}}{{/responseHeaders}}] + {{/hasResponseHeaders}} + {{#hasExamples}} + - examples: {{{examples}}} + {{/hasExamples}} + {{#externalDocs}} + - externalDocs: {{externalDocs}} + {{/externalDocs}} + {{#allParams}} + - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} + {{/allParams}} - returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}} */ open class func {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { @@ -127,16 +144,14 @@ open class {{classname}} { {{^hasFormParams}} let parameters: [String:Any]? = nil {{/hasFormParams}} - {{/bodyParam}} - - let url = NSURLComponents(string: URLString) - {{#hasQueryParams}} - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + {{/bodyParam}}{{#hasQueryParams}} + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ {{#queryParams}} {{> _param}}{{#hasMore}}, {{/hasMore}} {{/queryParams}} - ]) - {{/hasQueryParams}}{{#headerParams}}{{^secondaryParam}} + ]){{/hasQueryParams}}{{^hasQueryParams}} + let url = URLComponents(string: URLString){{/hasQueryParams}}{{#headerParams}}{{^secondaryParam}} let nillableHeaders: [String: Any?] = [{{/secondaryParam}} {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ] diff --git a/modules/openapi-generator/src/main/resources/swift4/modelObject.mustache b/modules/openapi-generator/src/main/resources/swift4/modelObject.mustache index 2add07f24ff0..e187c4943701 100644 --- a/modules/openapi-generator/src/main/resources/swift4/modelObject.mustache +++ b/modules/openapi-generator/src/main/resources/swift4/modelObject.mustache @@ -22,6 +22,13 @@ public struct {{classname}}: Codable { {{/isEnum}} {{/allVars}} +{{#hasVars}} + public init({{#allVars}}{{name}}: {{{datatypeWithEnum}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allVars}}) { + {{#allVars}} + self.{{name}} = {{name}} + {{/allVars}} + } +{{/hasVars}} {{#additionalPropertiesType}} public var additionalProperties: [String:{{{additionalPropertiesType}}}] = [:] diff --git a/modules/openapi-generator/src/main/resources/tizen/model-body.mustache b/modules/openapi-generator/src/main/resources/tizen/model-body.mustache index daed9148b2c2..97b31a38a9ee 100644 --- a/modules/openapi-generator/src/main/resources/tizen/model-body.mustache +++ b/modules/openapi-generator/src/main/resources/tizen/model-body.mustache @@ -23,10 +23,14 @@ using namespace Tizen::{{prefix}}; void {{classname}}::__init() { - //{{#vars}} - //{{#isContainer}}{{defaultValue}}{{baseType}}> {{name}};{{/isContainer}} - //{{#isNotContainer}}{{name}} = {{defaultValue}};{{/isNotContainer}} - //{{/vars}} + {{#vars}} + {{#isContainer}} + //{{defaultValue}}{{baseType}}> {{name}}; + {{/isContainer}} + {{#isNotContainer}} + //{{name}} = {{defaultValue}}; + {{/isNotContainer}} + {{/vars}} } void diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/api.module.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/api.module.mustache index f5afbdc552ef..06dad036e629 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/api.module.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/api.module.mustache @@ -22,7 +22,7 @@ export class ApiModule { return { ngModule: ApiModule, providers: [ { provide: Configuration, useFactory: configurationFactory } ] - } + }; } constructor( @Optional() @SkipSelf() parentModule: ApiModule, diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache index c8c8df6c0d67..01274db96bb4 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache @@ -64,7 +64,7 @@ export class {{classname}} { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -199,7 +199,7 @@ export class {{classname}} { {{/isBasic}} {{#isOAuth}} if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; {{#useHttpClient}}headers = {{/useHttpClient}}headers.set('Authorization', 'Bearer ' + accessToken); @@ -213,30 +213,30 @@ export class {{classname}} { '{{{mediaType}}}'{{#hasMore}},{{/hasMore}} {{/produces}} ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { {{^useHttpClient}} - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); {{/useHttpClient}} {{#useHttpClient}} - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); {{/useHttpClient}} } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ {{#consumes}} '{{{mediaType}}}'{{#hasMore}},{{/hasMore}} {{/consumes}} ]; {{#bodyParam}} - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { {{^useHttpClient}} headers.set('Content-Type', httpContentTypeSelected); {{/useHttpClient}} {{#useHttpClient}} - headers = headers.set("Content-Type", httpContentTypeSelected); + headers = headers.set('Content-Type', httpContentTypeSelected); {{/useHttpClient}} } {{/bodyParam}} diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/modelEnum.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/modelEnum.mustache index 932d3c0fb471..7ad77ac62a22 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/modelEnum.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/modelEnum.mustache @@ -6,4 +6,4 @@ export const {{classname}} = { {{name}}: {{{value}}} as {{classname}}{{^-last}},{{/-last}} {{/enumVars}} {{/allowableValues}} -} \ No newline at end of file +}; \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/modelGenericEnums.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/modelGenericEnums.mustache index 432020b726fa..eb450b57fcc7 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/modelGenericEnums.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/modelGenericEnums.mustache @@ -10,7 +10,7 @@ export namespace {{classname}} { {{name}}: {{{value}}} as {{enumName}}{{^-last}},{{/-last}} {{/enumVars}} {{/allowableValues}} - } + }; {{/isEnum}} {{/vars}} }{{/hasEnums}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/api.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/api.mustache index 86d0cbe8dcae..d149d5ff2eee 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/api.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/api.mustache @@ -85,7 +85,7 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur * @summary {{&summary}} {{/summary}} {{#allParams}} - * @param {{=<% %>=}}{<%dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} + * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} * @param {*} [options] Override http request option. * @throws {RequiredError} @@ -255,7 +255,7 @@ export const {{classname}}Fp = function(configuration?: Configuration) { * @summary {{&summary}} {{/summary}} {{#allParams}} - * @param {{=<% %>=}}{<%dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} + * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} * @param {*} [options] Override http request option. * @throws {RequiredError} @@ -290,7 +290,7 @@ export const {{classname}}Factory = function (configuration?: Configuration, fet * @summary {{&summary}} {{/summary}} {{#allParams}} - * @param {{=<% %>=}}{<%dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} + * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} * @param {*} [options] Override http request option. * @throws {RequiredError} @@ -302,6 +302,33 @@ export const {{classname}}Factory = function (configuration?: Configuration, fet }; }; +{{#withInterfaces}} +/** + * {{classname}} - interface{{#description}} + * {{&description}}{{/description}} + * @export + * @interface {{classname}} + */ +export interface {{classname}}Interface { +{{#operation}} + /** + * {{¬es}} + {{#summary}} + * @summary {{&summary}} + {{/summary}} + {{#allParams}} + * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} + {{/allParams}} + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof {{classname}}Interface + */ + {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: any): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}>; + +{{/operation}} +} + +{{/withInterfaces}} /** * {{classname}} - object-oriented interface{{#description}} * {{{description}}}{{/description}} @@ -309,7 +336,12 @@ export const {{classname}}Factory = function (configuration?: Configuration, fet * @class {{classname}} * @extends {BaseAPI} */ +{{#withInterfaces}} +export class {{classname}} extends BaseAPI implements {{classname}}Interface { +{{/withInterfaces}} +{{^withInterfaces}} export class {{classname}} extends BaseAPI { +{{/withInterfaces}} {{#operation}} /** * {{¬es}} @@ -317,7 +349,7 @@ export class {{classname}} extends BaseAPI { * @summary {{&summary}} {{/summary}} {{#allParams}} - * @param {{=<% %>=}}{<%%dataType%%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} + * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} * @param {*} [options] Override http request option. * @throws {RequiredError} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache index 4d8bd2f09a19..585b9825bfc7 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache @@ -11,7 +11,7 @@ export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ {{#vars}} /** * {{{description}}} - * @type {{=<% %>=}}{<%datatype%>}<%={{ }}=%> + * @type {{=<% %>=}}{<%&datatype%>}<%={{ }}=%> * @memberof {{classname}} */ {{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/ApiServiceBinder.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/ApiServiceBinder.mustache new file mode 100644 index 000000000000..0026933c69c8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/ApiServiceBinder.mustache @@ -0,0 +1,20 @@ +import {interfaces} from "inversify"; + +{{#apiInfo}} +{{#apis}} +import { {{classname}} } from './{{importPath}}'; +{{#withInterfaces}} +import { {{classname}}Interface } from './{{importPath}}Interface'; +{{/withInterfaces}} +{{/apis}} +{{/apiInfo}} + +export class ApiServiceBinder { + public static with(container: interfaces.Container) { + {{#apiInfo}} + {{#apis}} + container.bind<{{classname}}{{#withInterfaces}}Interface{{/withInterfaces}}>("{{classname}}").to({{classname}}).inSingletonScope(); + {{/apis}} + {{/apiInfo}} + } +} diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/Headers.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/Headers.mustache new file mode 100644 index 000000000000..0fa7760e01ea --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/Headers.mustache @@ -0,0 +1,3 @@ +export interface Headers { + [index:string]: string +} diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/HttpClient.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/HttpClient.mustache new file mode 100644 index 000000000000..64fe12a30452 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/HttpClient.mustache @@ -0,0 +1,63 @@ +import IHttpClient from "./IHttpClient"; +import { Observable } from "rxjs/Observable"; +import "whatwg-fetch"; +import HttpResponse from "./HttpResponse"; +import {injectable} from "inversify"; +import "rxjs/add/observable/fromPromise"; +import { Headers } from "./Headers"; + +@injectable() +class HttpClient implements IHttpClient { + + get(url:string, headers?: Headers):Observable { + return this.performNetworkCall(url, "get", undefined, headers); + } + + post(url: string, body: {}|FormData, headers?: Headers): Observable { + return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + put(url: string, body: {}, headers?: Headers): Observable { + return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + delete(url: string, headers?: Headers): Observable { + return this.performNetworkCall(url, "delete", undefined, headers); + } + + private getJsonBody(body: {}|FormData) { + return !(body instanceof FormData) ? JSON.stringify(body) : body; + } + + private addJsonHeaders(headers: Headers) { + return Object.assign({}, { + "Accept": "application/json", + "Content-Type": "application/json" + }, headers); + }; + + private performNetworkCall(url: string, method: string, body?: any, headers?: Headers): Observable { + let promise = window.fetch(url, { + method: method, + body: body, + headers: headers + }).then(response => { + let headers: Headers = {}; + response.headers.forEach((value, name) => { + headers[name.toString().toLowerCase()] = value; + }); + return response.text().then(text => { + let contentType = headers["content-type"] || ""; + let payload = contentType.match("application/json") ? JSON.parse(text) : text; + let httpResponse = new HttpResponse(payload, response.status, headers); + + if (response.status >= 400) + throw httpResponse; + return httpResponse; + }); + }); + return Observable.fromPromise(promise); + } +} + +export default HttpClient \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/HttpResponse.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/HttpResponse.mustache new file mode 100644 index 000000000000..411240cde2bd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/HttpResponse.mustache @@ -0,0 +1,8 @@ +import { Headers } from "./Headers" + +class HttpResponse { + constructor(public response: T, public status:number, public headers?: Headers) { + } +} + +export default HttpResponse \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/IAPIConfiguration.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/IAPIConfiguration.mustache new file mode 100644 index 000000000000..2364e83e6cb3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/IAPIConfiguration.mustache @@ -0,0 +1,8 @@ +export interface IAPIConfiguration { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/IHttpClient.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/IHttpClient.mustache new file mode 100644 index 000000000000..22d9e07c903e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/IHttpClient.mustache @@ -0,0 +1,12 @@ +import { Observable } from "rxjs/Observable"; +import HttpResponse from "./HttpResponse"; +import { Headers } from "./Headers"; + +interface IHttpClient { + get(url:string, headers?: Headers):Observable + post(url:string, body:{}|FormData, headers?: Headers):Observable + put(url:string, body:{}, headers?: Headers):Observable + delete(url:string, headers?: Headers):Observable +} + +export default IHttpClient \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/README.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/README.mustache new file mode 100644 index 000000000000..4da4e854d960 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/README.mustache @@ -0,0 +1,74 @@ +## {{npmName}}@{{npmVersion}} + +### Building + +To build an compile the typescript sources to javascript use: +``` +npm install +npm run build +``` + +### publishing + +First build the package than run ```npm publish``` + +### consuming + +navigate to the folder of your consuming project and run one of next commando's. + +_published:_ + +``` +npm install {{npmName}}@{{npmVersion}} --save +``` + +_unPublished (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE --save +``` + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE: +``` +npm link +``` + +In your project: +``` +npm link {{npmName}}@{{npmVersion}} +``` + +## Requirements +Services require a `IHttpClient` and a `IApiConfiguration`. The `IHttpClient` is necessary to manage http's call and with the `IApiConfiguration` you can provide settings for the Authentication. +For the sake of simplicity an implementation of `IHttpClient` is already provided, but if you want you can override it. +For these reasons you have to manually bind these two services: + +```typescript +let container = new Container(); +container.bind("IApiHttpClient").to(HttpClient).inSingletonScope(); +container.bind("IApiConfiguration").to(ApiConfiguration).inSingletonScope(); +``` + + +## Services Binding +To bind all the generated services you can use `ApiServiceBinder`. + +```typescript +ApiServiceBinder.with(container); +``` + +## Final result + +```typescript +let container = new Container(); +container.bind("IApiHttpClient").to(HttpClient).inSingletonScope(); +container.bind("IApiConfiguration").to(ApiConfiguration).inSingletonScope(); +ApiServiceBinder.with(container); +``` + + + + + diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/api.service.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/api.service.mustache new file mode 100644 index 000000000000..259583755766 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/api.service.mustache @@ -0,0 +1,180 @@ +{{>licenseInfo}} +/* tslint:disable:no-unused-variable member-ordering */ + +import { Observable } from "rxjs/Observable"; +import 'rxjs/add/operator/map'; +import 'rxjs/add/operator/toPromise'; +import IHttpClient from "../IHttpClient"; +import { inject, injectable } from "inversify"; +import { IAPIConfiguration } from "../IAPIConfiguration"; +import { Headers } from "../Headers"; +import HttpResponse from "../HttpResponse"; + +{{#imports}} +import { {{classname}} } from '../{{filename}}'; +{{/imports}} + +import { COLLECTION_FORMATS } from '../variables'; +{{#withInterfaces}} +import { {{classname}}Interface } from './{{classname}}Interface'; +{{/withInterfaces}} + +{{#operations}} + +{{#description}} +/** + * {{&description}} + */ +{{/description}} + +@injectable() +{{#withInterfaces}} +export class {{classname}} implements {{classname}}Interface { +{{/withInterfaces}} +{{^withInterfaces}} +export class {{classname}} { +{{/withInterfaces}} + private basePath: string = '{{{basePath}}}'; + + constructor(@inject("IApiHttpClient") private httpClient: IHttpClient, + @inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) { + if(this.APIConfiguration.basePath) + this.basePath = this.APIConfiguration.basePath; + } +{{#operation}} + + /** + * {{summary}} + * {{notes}} + {{#allParams}}* @param {{paramName}} {{description}} + {{/allParams}}{{#useHttpClient}}* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress.{{/useHttpClient}} + */ + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'body', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>; + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'response', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}>; + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe: any = 'body', headers: Headers = {}): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}} { +{{#allParams}} +{{#required}} + if (!{{paramName}}){ + throw new Error('Required parameter {{paramName}} was null or undefined when calling {{nickname}}.'); + } + +{{/required}} +{{/allParams}} +{{#hasQueryParams}} + let queryParameters: string[] = []; +{{#queryParams}} + {{#isListContainer}} + if ({{paramName}}) { + {{#isCollectionFormatMulti}} + {{paramName}}.forEach((element) => { + queryParameters.push("{{paramName}}="+encodeURIComponent(String({{paramName}}))); + }) + {{/isCollectionFormatMulti}} + {{^isCollectionFormatMulti}} + queryParameters.push("{{paramName}}="+encodeURIComponent({{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']))); + {{/isCollectionFormatMulti}} + } + {{/isListContainer}} + {{^isListContainer}} + if ({{paramName}} !== undefined) { + {{#isDateTime}} + queryParameters.push("{{paramName}}="+encodeURIComponent({{paramName}}.toISOString())); + {{/isDateTime}} + {{^isDateTime}} + queryParameters.push("{{paramName}}="+encodeURIComponent(String({{paramName}}))); + {{/isDateTime}} + } + {{/isListContainer}} +{{/queryParams}} + +{{/hasQueryParams}} +{{#headerParams}} + {{#isListContainer}} + if ({{paramName}}) { + headers['{{baseName}}'] = {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']); + } + {{/isListContainer}} + {{^isListContainer}} + if ({{paramName}}) { + headers['{{baseName}}'] = String({{paramName}}); + } + {{/isListContainer}} + +{{/headerParams}} +{{#authMethods}} + // authentication ({{name}}) required +{{#isApiKey}} +{{#isKeyInHeader}} + if (this.APIConfiguration.apiKeys["{{keyParamName}}"]) { + headers['{{keyParamName}}'] = this.APIConfiguration.apiKeys["{{keyParamName}}"]; + } +{{/isKeyInHeader}} +{{#isKeyInQuery}} + if (this.APIConfiguration.apiKeys["{{keyParamName}}"]) { + queryParameters.push("{{paramName}}="+encodeURIComponent(String(this.APIConfiguration.apiKeys["{{keyParamName}}"]))); + } +{{/isKeyInQuery}} +{{/isApiKey}} +{{#isBasic}} + if (this.APIConfiguration.username || this.APIConfiguration.password) { + headers['Authorization'] = btoa(this.APIConfiguration.username + ':' + this.APIConfiguration.password); + } +{{/isBasic}} +{{#isOAuth}} + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } +{{/isOAuth}} +{{/authMethods}} + {{^produces}} + headers['Accept'] = 'application/json'; + {{/produces}} + {{#produces.0}} + headers['Accept'] = '{{{mediaType}}}'; + {{/produces.0}} +{{#bodyParam}} + {{^consumes}} + headers['Content-Type'] = 'application/json'; + {{/consumes}} + {{#consumes.0}} + headers['Content-Type'] = '{{{mediaType}}}'; + {{/consumes.0}} +{{/bodyParam}} + +{{#hasFormParams}} + let formData: FormData = new FormData(); + headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; +{{#formParams}} + {{#isListContainer}} + if ({{paramName}}) { + {{#isCollectionFormatMulti}} + {{paramName}}.forEach((element) => { + formData.append('{{baseName}}', element); + }) + {{/isCollectionFormatMulti}} + {{^isCollectionFormatMulti}} + formData.append('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])); + {{/isCollectionFormatMulti}} + } + {{/isListContainer}} + {{^isListContainer}} + if ({{paramName}} !== undefined) { + formData.append('{{baseName}}', {{paramName}}); + } + {{/isListContainer}} +{{/formParams}} + +{{/hasFormParams}} + const response: Observable> = this.httpClient.{{httpMethod}}(`${this.basePath}{{{path}}}{{#hasQueryParams}}?${queryParameters.join('&')}{{/hasQueryParams}}`{{#bodyParam}}, {{paramName}} {{/bodyParam}}{{#hasFormParams}}, body{{/hasFormParams}}, headers); + if (observe == 'body') { + return response.map(httpResponse => <{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>(httpResponse.response)){{#usePromise}}.toPromise(){{/usePromise}}; + } + return response{{#usePromise}}.toPromise(){{/usePromise}}; + } + +{{/operation}}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/apiInterface.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/apiInterface.mustache new file mode 100644 index 000000000000..cb31c6396b9e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/apiInterface.mustache @@ -0,0 +1,26 @@ +{{>licenseInfo}} +import { Headers } from "../Headers"; +import { Observable } from "rxjs/Observable"; +import * as models from "../model/models"; +import HttpResponse from "../HttpResponse"; + +{{#operations}} + +{{#description}} + /** + * {{&description}} + */ +{{/description}} +export interface {{classname}}Interface { +{{#operation}} + /** + * {{summary}} + * {{notes}} + {{#allParams}}* @param {{paramName}} {{description}} + {{/allParams}}*/ + + {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'body', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>; + {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'response', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}>; +{{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/apis.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/apis.mustache new file mode 100644 index 000000000000..3d49b9488b48 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/apis.mustache @@ -0,0 +1,5 @@ +{{#apiInfo}} +{{#apis}} +export * from './{{ classFilename }}'; +{{/apis}} +{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/git_push.sh.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/git_push.sh.mustache new file mode 100755 index 000000000000..a2d752348373 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/git_push.sh.mustache @@ -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 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + 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/modules/openapi-generator/src/main/resources/typescript-inversify/gitignore b/modules/openapi-generator/src/main/resources/typescript-inversify/gitignore new file mode 100644 index 000000000000..23c3bdf9c9be --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/gitignore @@ -0,0 +1,6 @@ +wwwroot/*.js +node_modules +typings +dist +.vscode +.idea \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/index.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/index.mustache new file mode 100644 index 000000000000..54e1715c1e18 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/index.mustache @@ -0,0 +1,7 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './IAPIConfiguration'; +export * from './ApiServiceBinder'; +export * from './IHttpClient'; +export * from './HttpClient'; \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/licenseInfo.mustache new file mode 100644 index 000000000000..7d61c4ee0550 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/model.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/model.mustache new file mode 100644 index 000000000000..0b93ad2998f0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/model.mustache @@ -0,0 +1,16 @@ +{{>licenseInfo}} +{{#models}} +{{#model}} +{{#tsImports}} +import { {{classname}} } from './{{filename}}'; +{{/tsImports}} + + +{{#description}} +/** + * {{{description}}} + */ +{{/description}} +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#isAlias}}{{>modelAlias}}{{/isAlias}}{{^isAlias}}{{#taggedUnions}}{{>modelTaggedUnion}}{{/taggedUnions}}{{^taggedUnions}}{{>modelGeneric}}{{/taggedUnions}}{{/isAlias}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/modelAlias.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/modelAlias.mustache new file mode 100644 index 000000000000..c1c6bf7a5da6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/modelAlias.mustache @@ -0,0 +1 @@ +export type {{classname}} = {{dataType}}; \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/modelEnum.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/modelEnum.mustache new file mode 100644 index 000000000000..932d3c0fb471 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/modelEnum.mustache @@ -0,0 +1,9 @@ +export type {{classname}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}}; + +export const {{classname}} = { +{{#allowableValues}} +{{#enumVars}} + {{name}}: {{{value}}} as {{classname}}{{^-last}},{{/-last}} +{{/enumVars}} +{{/allowableValues}} +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/modelGeneric.mustache new file mode 100644 index 000000000000..a4248ea3da0f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/modelGeneric.mustache @@ -0,0 +1,10 @@ +export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ {{>modelGenericAdditionalProperties}} +{{#vars}} + {{#description}} + /** + * {{{description}}} + */ + {{/description}} + {{#isReadOnly}}readonly {{/isReadOnly}}{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; +{{/vars}} +}{{>modelGenericEnums}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache new file mode 100644 index 000000000000..e6499ce9d63f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache @@ -0,0 +1,5 @@ +{{#additionalPropertiesType}} + + [key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}}; + +{{/additionalPropertiesType}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/modelGenericEnums.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/modelGenericEnums.mustache new file mode 100644 index 000000000000..432020b726fa --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/modelGenericEnums.mustache @@ -0,0 +1,16 @@ +{{#hasEnums}} + +export namespace {{classname}} { +{{#vars}} + {{#isEnum}} + export type {{enumName}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}}; + export const {{enumName}} = { + {{#allowableValues}} + {{#enumVars}} + {{name}}: {{{value}}} as {{enumName}}{{^-last}},{{/-last}} + {{/enumVars}} + {{/allowableValues}} + } + {{/isEnum}} +{{/vars}} +}{{/hasEnums}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/modelTaggedUnion.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/modelTaggedUnion.mustache new file mode 100644 index 000000000000..cd7d1c8b936a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/modelTaggedUnion.mustache @@ -0,0 +1,21 @@ +{{#discriminator}} +export type {{classname}} = {{#children}}{{^-first}} | {{/-first}}{{classname}}{{/children}}; +{{/discriminator}} +{{^discriminator}} +{{#parent}} +export interface {{classname}} { {{>modelGenericAdditionalProperties}} +{{#allVars}} + {{#description}} + /** + * {{{description}}} + */ + {{/description}} + {{name}}{{^required}}?{{/required}}: {{#discriminatorValue}}'{{discriminatorValue}}'{{/discriminatorValue}}{{^discriminatorValue}}{{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}{{/discriminatorValue}}; +{{/allVars}} +} +{{>modelGenericEnums}} +{{/parent}} +{{^parent}} +{{>modelGeneric}} +{{/parent}} +{{/discriminator}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/models.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/models.mustache new file mode 100644 index 000000000000..02a39c248c4d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/models.mustache @@ -0,0 +1,5 @@ +{{#models}} +{{#model}} +export * from './{{{ classFilename }}}'; +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/package.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/package.mustache new file mode 100644 index 000000000000..9733f2058a51 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/package.mustache @@ -0,0 +1,29 @@ +{ + "name": "{{{npmName}}}", + "version": "{{{npmVersion}}}", + "description": "swagger client for {{{npmName}}}", + "author": "Swagger Codegen Contributors", + "keywords": [ + "swagger-client" + ], + "license": "Unlicense", + "main": "dist/index.js", + "typings": "dist/index.d.ts", + "scripts": { + "build": "tsc --outDir dist/", + "postinstall": "npm run build" + }, + "dependencies": { + "inversify": "^4.3.0", + "rxjs": "~5.5.7", + "whatwg-fetch": "~2.0.1", + "reflect-metadata": "0.1.8" + }, + "devDependencies": { + }{{#npmRepository}},{{/npmRepository}} +{{#npmRepository}} + "publishConfig": { + "registry": "{{{npmRepository}}}" + } +{{/npmRepository}} +} diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/tsconfig.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/tsconfig.mustache new file mode 100644 index 000000000000..3ed5f2c0b100 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/tsconfig.mustache @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}", + "module": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}commonjs{{/supportsES6}}", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./dist", + "noLib": false, + "declaration": true, + "lib": [ "es6", "dom" ] + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] +} diff --git a/modules/openapi-generator/src/main/resources/typescript-inversify/variables.mustache b/modules/openapi-generator/src/main/resources/typescript-inversify/variables.mustache new file mode 100644 index 000000000000..5d3805255c2e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-inversify/variables.mustache @@ -0,0 +1,6 @@ +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/modules/openapi-generator/src/main/resources/typescript-node/api.mustache b/modules/openapi-generator/src/main/resources/typescript-node/api.mustache index 58cd4b31bf15..d95cbbbddb86 100644 --- a/modules/openapi-generator/src/main/resources/typescript-node/api.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-node/api.mustache @@ -141,7 +141,7 @@ export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ * {{{description}}} */ {{/description}} - '{{name}}': {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + '{{name}}'{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} {{#discriminator}} @@ -151,6 +151,7 @@ export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ static discriminator = undefined; {{/discriminator}} + {{^isArrayModel}} static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ {{#vars}} { @@ -170,6 +171,7 @@ export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ return {{classname}}.attributeTypeMap; {{/parent}} } + {{/isArrayModel}} } {{#hasEnums}} @@ -220,8 +222,9 @@ export interface Authentication { } export class HttpBasicAuth implements Authentication { - public username: string; - public password: string; + public username: string = ''; + public password: string = ''; + applyToRequest(requestOptions: localVarRequest.Options): void { requestOptions.auth = { username: this.username, password: this.password @@ -230,7 +233,7 @@ export class HttpBasicAuth implements Authentication { } export class ApiKeyAuth implements Authentication { - public apiKey: string; + public apiKey: string = ''; constructor(private location: string, private paramName: string) { } @@ -245,7 +248,7 @@ export class ApiKeyAuth implements Authentication { } export class OAuth implements Authentication { - public accessToken: string; + public accessToken: string = ''; applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { @@ -255,8 +258,9 @@ export class OAuth implements Authentication { } export class VoidAuth implements Authentication { - public username: string; - public password: string; + public username: string = ''; + public password: string = ''; + applyToRequest(_: localVarRequest.Options): void { // Do nothing } diff --git a/modules/openapi-generator/src/main/resources/undertow/formParams.mustache b/modules/openapi-generator/src/main/resources/undertow/formParams.mustache index e44ab167e8f3..100c391f8ebc 100644 --- a/modules/openapi-generator/src/main/resources/undertow/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/undertow/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}{{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/undertow/openapi.mustache b/modules/openapi-generator/src/main/resources/undertow/openapi.mustache new file mode 100644 index 000000000000..7710186d9d5c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/undertow/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-json}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/undertow/swagger.mustache b/modules/openapi-generator/src/main/resources/undertow/swagger.mustache deleted file mode 100644 index 0a7a20061553..000000000000 --- a/modules/openapi-generator/src/main/resources/undertow/swagger.mustache +++ /dev/null @@ -1 +0,0 @@ -{{{swagger-json}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java deleted file mode 100644 index a8a9cd6fcbd5..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.openapitools.codegen; - -import static org.openapitools.codegen.testutils.AssertFile.assertPathEqualsRecursively; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.testng.annotations.Test; -import org.testng.reporters.Files; - -import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; - -public abstract class AbstractIntegrationTest { - - protected abstract IntegrationTestPathsConfig getIntegrationTestPathsConfig(); - - protected abstract CodegenConfig getCodegenConfig(); - - protected abstract Map configProperties(); - - protected Boolean generateSwaggerMetadata = true; - - protected Map systemPropertyOverrides = new HashMap<>(); - - // @wing328: ignore for the time being until we fix the error with the integration test - @Test(enabled = false) - public void generatesCorrectDirectoryStructure() throws IOException { - DefaultGenerator codeGen = new DefaultGenerator(); - codeGen.setGenerateSwaggerMetadata(generateSwaggerMetadata); - for (Map.Entry propertyOverride : systemPropertyOverrides.entrySet()) { - codeGen.setGeneratorPropertyDefault(propertyOverride.getKey(), propertyOverride.getValue()); - } - - IntegrationTestPathsConfig integrationTestPathsConfig = getIntegrationTestPathsConfig(); - - String specContent = Files.readFile(integrationTestPathsConfig.getSpecPath().toFile()); - Swagger swagger = new SwaggerParser().parse(specContent); - - CodegenConfig codegenConfig = getCodegenConfig(); - codegenConfig.setOutputDir(integrationTestPathsConfig.getOutputPath().toString()); - codegenConfig.setIgnoreFilePathOverride(integrationTestPathsConfig.getIgnoreFilePath().toFile().toString()); - ClientOpts clientOpts = new ClientOpts(); - clientOpts.setProperties(configProperties()); - ClientOptInput opts = new ClientOptInput() - .config(codegenConfig) - .opts(clientOpts) - .swagger(swagger); - - codeGen.opts(opts).generate(); - - assertPathEqualsRecursively(integrationTestPathsConfig.getExpectedPath(), integrationTestPathsConfig.getOutputPath()); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/ClientAuthInputTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/ClientAuthInputTest.java deleted file mode 100644 index 1a23f23efbef..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/ClientAuthInputTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.openapitools.codegen; - -import io.swagger.models.auth.AuthorizationValue; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.List; - -@SuppressWarnings("static-method") -public class ClientAuthInputTest { - - @Test(description = "read a file upload param from a 2.0 spec") - public void clientAuthInputTest() { - final ClientOptInput input = new ClientOptInput(); - - final String header = "api_key:special-key,api_key:hello,X-AUTHORIZATION:0e6c11d79a,Authorization:Basic 1jz0"; - input.setAuth(header); - final List authValues = input.getAuthorizationValues(); - Assert.assertEquals(authValues.size(), 4); - - final AuthorizationValue a1 = authValues.get(0); - Assert.assertEquals(a1.getKeyName(), "api_key"); - Assert.assertEquals(a1.getValue(), "special-key"); - Assert.assertEquals(a1.getType(), "header"); - - final AuthorizationValue a2 = authValues.get(1); - Assert.assertEquals(a2.getKeyName(), "api_key"); - Assert.assertEquals(a2.getValue(), "hello"); - Assert.assertEquals(a2.getType(), "header"); - - final AuthorizationValue a3 = authValues.get(2); - Assert.assertEquals(a3.getKeyName(), "X-AUTHORIZATION"); - Assert.assertEquals(a3.getValue(), "0e6c11d79a"); - Assert.assertEquals(a3.getType(), "header"); - - final AuthorizationValue a4 = authValues.get(3); - Assert.assertEquals(a4.getKeyName(), "Authorization"); - Assert.assertEquals(a4.getValue(), "Basic 1jz0"); - Assert.assertEquals(a4.getType(), "header"); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java deleted file mode 100644 index d538c75b681d..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.openapitools.codegen; - -import org.reflections.Reflections; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import static org.testng.Assert.assertEquals; - -@SuppressWarnings("static-method") -public class CodegenConfigLoaderTest { - - @DataProvider(name = "codegenConfig") - public Object[][] createCodegenConfigDataSet() throws Exception { - - Reflections reflections = new Reflections("org.openapitools.codegen.languages"); - final Set> subTypesOf = reflections.getSubTypesOf(DefaultCodegen.class); - - List codegenConfigList = new ArrayList(); - - for (Class aClass : subTypesOf) { - if (!Modifier.isAbstract(aClass.getModifiers())) { - final DefaultCodegen defaultCodegen = aClass.newInstance(); - codegenConfigList.add((CodegenConfig) defaultCodegen); - } - } - - Object[][] result = new Object[codegenConfigList.size()][1]; - - for (int i = 0; i < codegenConfigList.size(); i++) { - result[i]= new Object[]{codegenConfigList.get(i)}; - } - - return result; - } - - @Test(dataProvider = "codegenConfig") - public void testLoadByName(CodegenConfig codegenConfig) throws Exception { - final CodegenConfig loadedConfig = CodegenConfigLoader.forName(codegenConfig.getName()); - - assertEquals(loadedConfig.getClass(), codegenConfig.getClass()); - assertEquals(loadedConfig.getName(), codegenConfig.getName()); - } - - @Test(dataProvider = "codegenConfig") - public void testLoadByFullQualifiedName(CodegenConfig codegenConfig) throws Exception { - final CodegenConfig loadedConfig = CodegenConfigLoader.forName(codegenConfig.getClass().getName()); - - assertEquals(loadedConfig.getClass(), codegenConfig.getClass()); - assertEquals(loadedConfig.getName(), codegenConfig.getName()); - - - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/CodegenTest.java deleted file mode 100644 index b9dba1d43465..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/CodegenTest.java +++ /dev/null @@ -1,434 +0,0 @@ -package org.openapitools.codegen; - -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.models.properties.Property; -import io.swagger.parser.SwaggerParser; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.List; - -public class CodegenTest { - - @Test(description = "test sanitizeTag") - public void sanitizeTagTest() { - final DefaultCodegen codegen = new DefaultCodegen(); - Assert.assertEquals(codegen.sanitizeTag("foo"), "Foo"); - Assert.assertEquals(codegen.sanitizeTag("$foo!"), "Foo"); - Assert.assertEquals(codegen.sanitizeTag("foo bar"), "FooBar"); - Assert.assertEquals(codegen.sanitizeTag("foo_bar"), "FooBar"); - Assert.assertEquals(codegen.sanitizeTag("foo1 bar2"), "Foo1Bar2"); - Assert.assertEquals(codegen.sanitizeTag("foo bar 1"), "FooBar1"); - Assert.assertEquals(codegen.sanitizeTag("1foo"), "Class1foo"); - } - - @Test(description = "test underscore") - public void underscoreNamesTest() { - final DefaultCodegen codegen = new DefaultCodegen(); - - Assert.assertEquals(codegen.underscore("foo"), "foo"); - Assert.assertEquals(codegen.underscore("foo-bar"), "foo_bar"); - Assert.assertEquals(codegen.underscore("foo bar"), "foo_bar"); - - Assert.assertEquals(codegen.underscore("FooBar"), "foo_bar"); - Assert.assertEquals(codegen.underscore("FooBarBaz"), "foo_bar_baz"); - } - - @Test(description = "test camelize") - public void camelizeNamesTest() { - final DefaultCodegen codegen = new DefaultCodegen(); - - Assert.assertEquals(codegen.camelize("foo"), "Foo"); - Assert.assertEquals(codegen.camelize(".foo"), "Foo"); - Assert.assertEquals(codegen.camelize(".foo.bar"), "FooBar"); - Assert.assertEquals(codegen.camelize("foo$bar"), "Foo$bar"); - Assert.assertEquals(codegen.camelize("foo_$bar"), "Foo$bar"); - - Assert.assertEquals(codegen.camelize("foo_bar"), "FooBar"); - Assert.assertEquals(codegen.camelize("foo_bar_baz"), "FooBarBaz"); - Assert.assertEquals(codegen.camelize("foo/bar.baz"), "FooBarBaz"); - Assert.assertEquals(codegen.camelize("/foo/bar/baz.qux/corge"), "FooBarBazQuxCorge"); - Assert.assertEquals(codegen.camelize("foo-bar"), "FooBar"); - Assert.assertEquals(codegen.camelize("foo-bar-xyzzy"), "FooBarXyzzy"); - } - - @Test(description = "read a file upload param from a 2.0 spec") - public void fileUploadParamTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/petstore.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/pet/{petId}/uploadImage"; - final Operation p = model.getPaths().get(path).getPost(); - final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); - - Assert.assertEquals(op.operationId, "uploadFile"); - Assert.assertEquals(op.httpMethod, "POST"); - Assert.assertTrue(op.hasConsumes); - Assert.assertEquals(op.consumes.size(), 1); - Assert.assertEquals(op.consumes.get(0).get("mediaType"), "multipart/form-data"); - Assert.assertTrue(op.hasProduces); - Assert.assertEquals(op.allParams.size(), 3); - Assert.assertEquals(op.formParams.size(), 2); - - final CodegenParameter file = op.formParams.get(1); - Assert.assertTrue(file.isFormParam); - Assert.assertEquals(file.dataType, "File"); - Assert.assertFalse(file.required); - Assert.assertTrue(file.isFile); - Assert.assertFalse(file.hasMore); - } - - @Test(description = "read formParam values from a 2.0 spec") - public void formParamTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/petstore.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/pet/{petId}"; - final Operation p = model.getPaths().get(path).getPost(); - final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); - - Assert.assertEquals(op.operationId, "updatePetWithForm"); - Assert.assertEquals(op.httpMethod, "POST"); - Assert.assertTrue(op.hasConsumes); - Assert.assertEquals(op.consumes.size(), 1); - Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/x-www-form-urlencoded"); - Assert.assertTrue(op.hasProduces); - Assert.assertEquals(op.produces.size(), 2); - Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/json"); - Assert.assertEquals(op.produces.get(0).get("hasMore"), "true"); - Assert.assertEquals(op.produces.get(1).get("mediaType"), "application/xml"); - Assert.assertEquals(op.pathParams.size(), 1); - - final CodegenParameter idParam = op.pathParams.get(0); - Assert.assertTrue(idParam.isPathParam); - Assert.assertEquals(idParam.dataType, "String"); - Assert.assertTrue(idParam.required); - Assert.assertFalse(idParam.hasMore); - - Assert.assertEquals(op.allParams.size(), 3); - Assert.assertEquals(op.formParams.size(), 2); - - final CodegenParameter nameParam = op.formParams.get(0); - Assert.assertTrue(nameParam.isFormParam); - Assert.assertTrue(nameParam.notFile); - Assert.assertEquals(nameParam.dataType, "String"); - Assert.assertFalse(nameParam.required); - Assert.assertTrue(nameParam.hasMore); - - final CodegenParameter statusParam = op.formParams.get(1); - Assert.assertTrue(statusParam.isFormParam); - Assert.assertTrue(statusParam.notFile); - Assert.assertEquals(statusParam.dataType, "String"); - Assert.assertFalse(statusParam.required); - Assert.assertFalse(statusParam.hasMore); - } - - @Test(description = "handle enum array in query parameter test") - public void enumArrayQueryParameterTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/petstore.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/pet/findByStatus"; - final Operation p = model.getPaths().get(path).getGet(); - final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); - - Assert.assertEquals(op.queryParams.size(), 1); - - final CodegenParameter statusParam = op.queryParams.get(0); - Assert.assertEquals(statusParam.items.datatypeWithEnum, "StatusEnum"); - Assert.assertNotNull(statusParam.items); - Assert.assertTrue(statusParam.items.isEnum); - Assert.assertEquals(statusParam.items._enum.size(), 3); - } - - @Test(description = "handle enum in query parameter test") - public void enumQueryParameterTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/petstore.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/pet/findByStatus"; - final Operation p = model.getPaths().get(path).getGet(); - final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); - - Assert.assertEquals(op.queryParams.size(), 1); - - final CodegenParameter statusParam = op.queryParams.get(0); - Assert.assertEquals(statusParam.datatypeWithEnum, "List"); - Assert.assertEquals(statusParam.baseType, "String"); - Assert.assertTrue(statusParam.isEnum); - Assert.assertEquals(((List)statusParam.allowableValues.get("values")).size(), 3); - } - - - @Test(description = "handle required parameters from a 2.0 spec as required when figuring out Swagger types") - public void requiredParametersTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/requiredTest.json"); - - final DefaultCodegen codegen = new DefaultCodegen() { - @Override - public String getSwaggerType(Property p) { - if (p != null && !p.getRequired()) { - return "Optional<" + super.getSwaggerType(p) + ">"; - } - return super.getSwaggerType(p); - } - }; - final String path = "/tests/requiredParams"; - final Operation p = model.getPaths().get(path).getGet(); - final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); - - final List formParams = op.formParams; - Assert.assertEquals(formParams.size(), 2); - Assert.assertEquals(formParams.get(0).dataType, "Long"); - Assert.assertEquals(formParams.get(1).dataType, "Optional"); - Assert.assertEquals(op.returnType, "Long"); - } - - @Test(description = "select main response from a 2.0 spec using the lowest 2XX code") - public void responseSelectionTest1() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/responseSelectionTest.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/tests/withTwoHundredAndDefault"; - final Operation p = model.getPaths().get(path).getGet(); - final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); - - Assert.assertEquals(op.returnType, "String"); - } - - @Test(description = "select main response from a 2.0 spec using the default keyword when no 2XX code") - public void responseSelectionTest2() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/responseSelectionTest.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/tests/withoutTwoHundredButDefault"; - final Operation p = model.getPaths().get(path).getGet(); - final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); - - Assert.assertEquals(op.returnType, "String"); - } - - @Test(description = "return byte array when response format is byte") - public void binaryDataTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/binaryDataTest.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/tests/binaryResponse"; - final Operation p = model.getPaths().get(path).getPost(); - final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); - - Assert.assertEquals(op.returnType, "byte[]"); - Assert.assertEquals(op.bodyParam.dataType, "byte[]"); - Assert.assertTrue(op.bodyParam.isBinary); - Assert.assertTrue(op.responses.get(0).isBinary); - } - - @Test(description = "return file when response format is file") - public void fileResponeseTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/fileResponseTest.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/tests/fileResponse"; - final Operation p = model.getPaths().get(path).getGet(); - final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); - - Assert.assertEquals(op.returnType, "File"); - Assert.assertTrue(op.responses.get(0).isFile); - Assert.assertTrue(op.isResponseFile); - } - - @Test(description = "discriminator is present") - public void discriminatorTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/discriminatorTest.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/pets"; - final Operation p = model.getPaths().get(path).getGet(); - final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); - - Assert.assertEquals(op.discriminator, "className"); - } - - @Test(description = "handle simple composition") - public void simpleCompositionTest() { - final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); - final DefaultCodegen codegen = new DefaultCodegen(); - codegen.supportsInheritance = true; - final Model model = swagger.getDefinitions().get("SimpleComposition"); - CodegenModel composed = codegen.fromModel("SimpleComposition", model, swagger.getDefinitions()); - - Assert.assertEquals(composed.vars.size(), 3); - Assert.assertEquals(composed.vars.get(0).baseName, "modelOneProp"); - Assert.assertEquals(composed.vars.get(1).baseName, "modelTwoProp"); - Assert.assertEquals(composed.vars.get(2).baseName, "simpleCompositionProp"); - Assert.assertNull(composed.parent); - } - - @Test(description = "handle multi level composition") - public void multiCompositionTest() { - final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); - final DefaultCodegen codegen = new DefaultCodegen(); - codegen.supportsInheritance = true; - final Model model = swagger.getDefinitions().get("CompositionOfSimpleComposition"); - CodegenModel composed = codegen.fromModel("CompositionOfSimpleComposition", model, swagger.getDefinitions()); - - Assert.assertEquals(composed.vars.size(), 5); - Assert.assertEquals(composed.vars.get(0).baseName, "modelOneProp"); - Assert.assertEquals(composed.vars.get(1).baseName, "modelTwoProp"); - Assert.assertEquals(composed.vars.get(2).baseName, "simpleCompositionProp"); - Assert.assertEquals(composed.vars.get(3).baseName, "modelThreeProp"); - Assert.assertEquals(composed.vars.get(4).baseName, "compositionOfSimpleCompositionProp"); - Assert.assertNull(composed.parent); - } - - @Test(description = "handle simple inheritance") - public void simpleInheritanceTest() { - final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); - final DefaultCodegen codegen = new DefaultCodegen(); - codegen.supportsInheritance = true; - final Model model = swagger.getDefinitions().get("ChildOfSimpleParent"); - CodegenModel child = codegen.fromModel("ChildOfSimpleParent", model, swagger.getDefinitions()); - - Assert.assertEquals(child.vars.size(), 2); - Assert.assertEquals(child.vars.get(0).baseName, "modelOneProp"); - Assert.assertEquals(child.vars.get(1).baseName, "childOfSimpleParentProp"); - Assert.assertEquals(child.parent, "SimpleParent"); - } - - @Test(description = "handle multi level inheritance") - public void multiInheritanceTest() { - final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); - final DefaultCodegen codegen = new DefaultCodegen(); - codegen.supportsInheritance = true; - final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); - CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); - - Assert.assertEquals(child.vars.size(), 1); - Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfSimpleParentProp"); - Assert.assertEquals(child.parent, "ChildOfSimpleParent"); - } - - @Test(description = "copy properties in multi level inheritance if supportsInheritance is false") - public void noSupportsInheritanceTest() { - final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); - final DefaultCodegen codegen = new DefaultCodegen(); - final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); - CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); - - Assert.assertEquals(child.vars.size(), 5); - Assert.assertEquals(child.vars.get(0).baseName, "modelOneProp"); - Assert.assertEquals(child.vars.get(1).baseName, "disc"); - Assert.assertEquals(child.vars.get(2).baseName, "simpleParentProp"); - Assert.assertEquals(child.vars.get(3).baseName, "childOfSimpleParentProp"); - Assert.assertEquals(child.vars.get(4).baseName, "childOfChildOfSimpleParentProp"); - Assert.assertEquals(child.parent, "ChildOfSimpleParent"); - } - - @Test(description = "don't copy interfaces properties if supportsMixins is true") - public void supportsMixinsTest() { - final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); - final DefaultCodegen codegen = new DefaultCodegen(); - codegen.supportsInheritance = true; - codegen.supportsMixins = true; - final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); - CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); - - Assert.assertEquals(child.vars.size(), 1); - Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfSimpleParentProp"); - Assert.assertEquals(child.allVars.size(), 5); - Assert.assertEquals(child.allVars.get(0).baseName, "modelOneProp"); - Assert.assertEquals(child.allVars.get(1).baseName, "disc"); - Assert.assertEquals(child.allVars.get(2).baseName, "simpleParentProp"); - Assert.assertEquals(child.allVars.get(3).baseName, "childOfSimpleParentProp"); - Assert.assertEquals(child.allVars.get(4).baseName, "childOfChildOfSimpleParentProp"); - - Assert.assertEquals(child.parent, "ChildOfSimpleParent"); - } - - @Test(description = "handle inheritance from composed model") - public void inheritanceOfComposedModelTest() { - final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); - final DefaultCodegen codegen = new DefaultCodegen(); - codegen.supportsInheritance = true; - final Model model = swagger.getDefinitions().get("ChildOfComposedParent"); - CodegenModel child = codegen.fromModel("ChildOfComposedParent", model, swagger.getDefinitions()); - - Assert.assertEquals(child.vars.size(), 1); - Assert.assertEquals(child.vars.get(0).baseName, "childOfComposedParentProp"); - Assert.assertEquals(child.parent, "ComposedParent"); - } - - @Test(description = "handle multi level inheritance from composed model") - public void multiInheritanceOfComposedModelTest() { - final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); - final DefaultCodegen codegen = new DefaultCodegen(); - codegen.supportsInheritance = true; - final Model model = swagger.getDefinitions().get("ChildOfChildOfComposedParent"); - CodegenModel child = codegen.fromModel("ChildOfChildOfComposedParent", model, swagger.getDefinitions()); - - Assert.assertEquals(child.vars.size(), 1); - Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfComposedParentProp"); - Assert.assertEquals(child.parent, "ChildOfComposedParent"); - } - - - @Test(description = "use operation consumes and produces") - public void localConsumesAndProducesTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/tests/localConsumesAndProduces"; - final Operation p = model.getPaths().get(path).getGet(); - CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); - - Assert.assertTrue(op.hasConsumes); - Assert.assertEquals(op.consumes.size(), 1); - Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/json"); - Assert.assertTrue(op.hasProduces); - Assert.assertEquals(op.produces.size(), 1); - Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/json"); - } - - @Test(description = "use spec consumes and produces") - public void globalConsumesAndProducesTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/tests/globalConsumesAndProduces"; - final Operation p = model.getPaths().get(path).getGet(); - CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); - - Assert.assertTrue(op.hasConsumes); - Assert.assertEquals(op.consumes.size(), 1); - Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/global_consumes"); - Assert.assertTrue(op.hasProduces); - Assert.assertEquals(op.produces.size(), 1); - Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/global_produces"); - } - - @Test(description = "use operation consumes and produces (reset in operation with empty array)") - public void localResetConsumesAndProducesTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/tests/localResetConsumesAndProduces"; - final Operation p = model.getPaths().get(path).getGet(); - CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); - - Assert.assertNotNull(op); - Assert.assertFalse(op.hasConsumes); - Assert.assertNull(op.consumes); - Assert.assertFalse(op.hasProduces); - Assert.assertNull(op.produces); - - } - - private static Swagger parseAndPrepareSwagger(String path) { - Swagger swagger = new SwaggerParser().read(path); - // resolve inline models - new InlineModelResolver().flatten(swagger); - return swagger; - } - - @Test(description = "isDeprecated is present") - public void deprecatedParamTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/petstore.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/pet/findByTags"; - final Operation p = model.getPaths().get(path).getGet(); - final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); - - Assert.assertTrue(op.isDeprecated); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java deleted file mode 100644 index f53a4ad1c5d1..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java +++ /dev/null @@ -1,529 +0,0 @@ -package org.openapitools.codegen; - -import org.openapitools.codegen.languages.JavaClientCodegen; -import io.swagger.models.ExternalDocs; -import io.swagger.models.Swagger; -import io.swagger.models.Tag; -import io.swagger.parser.SwaggerParser; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringUtils; -import org.junit.rules.TemporaryFolder; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.*; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.*; - -import static org.openapitools.codegen.CodegenConstants.TEMPLATE_DIR; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.fail; -import static org.testng.Assert.*; - -/** - * Tests for DefaultGenerator logic - */ -public class DefaultGeneratorTest { - - private static final String TEST_SKIP_OVERWRITE = "testSkipOverwrite"; - private static final String POM_FILE = "pom.xml"; - private static final String MODEL_ORDER_FILE = "/src/main/java/io/swagger/client/model/Order.java"; - private static final String API_CLIENT_FILE = "/src/main/java/io/swagger/client/ApiClient.java"; - private static final String BUILD_GRADLE_FILE = "build.gradle"; - - private static final String LIBRARY_COMMENT = "//overloaded template file within library folder to add this comment"; - private static final String TEMPLATE_COMMENT = "//overloaded main template file to add this comment"; - - public TemporaryFolder folder = new TemporaryFolder(); - - @BeforeMethod - public void setUp() throws Exception { - folder.create(); - } - - @AfterMethod - public void tearDown() throws Exception { - folder.delete(); - } - - @Test - public void testSecurityWithoutGlobal() throws Exception { - final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/petstore.json"); - CodegenConfig codegenConfig = new JavaClientCodegen(); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - - DefaultGenerator gen = new DefaultGenerator(); - gen.opts(clientOptInput); - Map> paths = gen.processPaths(swagger.getPaths()); - - CodegenSecurity cs, apiKey, petstoreAuth; - - // security of "getPetById": api_key - CodegenOperation getPetById = findCodegenOperationByOperationId(paths, "getPetById"); - assertEquals(getPetById.authMethods.size(), 2); - cs = getPetById.authMethods.get(0); - if ("api_key".equals(cs.name)) { - apiKey = cs; - petstoreAuth = getPetById.authMethods.get(1); - } else { - petstoreAuth = cs; - apiKey = getPetById.authMethods.get(1); - } - assertEquals(petstoreAuth.name, "petstore_auth"); - assertEquals(petstoreAuth.type, "oauth2"); - - - assertEquals(apiKey.name, "api_key"); - assertEquals(apiKey.type, "apiKey"); - - // security of "updatePetWithForm": petstore_auth - CodegenOperation updatePetWithForm = findCodegenOperationByOperationId(paths, "updatePetWithForm"); - assertEquals(updatePetWithForm.authMethods.size(), 1); - petstoreAuth = updatePetWithForm.authMethods.iterator().next(); - assertEquals(petstoreAuth.name, "petstore_auth"); - assertEquals(petstoreAuth.type, "oauth2"); - - // security of "loginUser": null (no global security either) - CodegenOperation loginUser = findCodegenOperationByOperationId(paths, "loginUser"); - assertNull(loginUser.authMethods); - } - - @Test - public void testSecurityWithGlobal() throws Exception { - final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/globalSecurity.json"); - CodegenConfig codegenConfig = new JavaClientCodegen(); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - - DefaultGenerator gen = new DefaultGenerator(); - gen.opts(clientOptInput); - Map> paths = gen.processPaths(swagger.getPaths()); - - CodegenSecurity cs, apiKey, apiKey2, petstoreAuth; - - // security of "getPetById": api_key - CodegenOperation getPetById = findCodegenOperationByOperationId(paths, "getPetById"); - assertEquals(getPetById.authMethods.size(), 2); - cs = getPetById.authMethods.get(0); - if ("api_key".equals(cs.name)) { - apiKey = cs; - petstoreAuth = getPetById.authMethods.get(1); - } else { - petstoreAuth = cs; - apiKey = getPetById.authMethods.get(1); - } - assertEquals(petstoreAuth.type, "oauth2"); - assertEquals(petstoreAuth.name, "petstore_auth"); - assertEquals(apiKey.name, "api_key"); - assertEquals(apiKey.type, "apiKey"); - - // security of "updatePetWithForm": petstore_auth - CodegenOperation updatePetWithForm = findCodegenOperationByOperationId(paths, "updatePetWithForm"); - assertEquals(updatePetWithForm.authMethods.size(), 1); - petstoreAuth = updatePetWithForm.authMethods.iterator().next(); - assertEquals(petstoreAuth.name, "petstore_auth"); - assertEquals(petstoreAuth.type, "oauth2"); - - // security of "loginUser": api_key, petstore_auth (from global security) - CodegenOperation loginUser = findCodegenOperationByOperationId(paths, "loginUser"); - assertEquals(loginUser.authMethods.size(), 2); - cs = loginUser.authMethods.get(0); - if ("api_key".equals(cs.name)) { - apiKey = cs; - petstoreAuth = loginUser.authMethods.get(1); - } else { - petstoreAuth = cs; - apiKey = loginUser.authMethods.get(1); - } - assertEquals(apiKey.name, "api_key"); - assertEquals(apiKey.type, "apiKey"); - assertEquals(petstoreAuth.name, "petstore_auth"); - assertEquals(petstoreAuth.type, "oauth2"); - - // security of "logoutUser": null (override global security) - CodegenOperation logoutUser = findCodegenOperationByOperationId(paths, "logoutUser"); - assertNull(logoutUser.authMethods); - - // security of "getUserByName": api_key, api_key2 (override global security) - CodegenOperation getUserByName = findCodegenOperationByOperationId(paths, "getUserByName"); - assertEquals(getUserByName.authMethods.size(), 2); - cs = getUserByName.authMethods.get(0); - if ("api_key".equals(cs.name)) { - apiKey = cs; - apiKey2 = getUserByName.authMethods.get(1); - } else { - apiKey2 = cs; - apiKey = getUserByName.authMethods.get(1); - } - assertEquals(apiKey.name, "api_key"); - assertEquals(apiKey.type, "apiKey"); - assertEquals(apiKey2.name, "api_key2"); - assertEquals(apiKey2.type, "apiKey"); - } - - @Test - public void testSkipOverwrite() throws Exception { - final File output = folder.getRoot(); - - final Swagger swagger = new SwaggerParser().read("src/test/resources/petstore.json"); - CodegenConfig codegenConfig = new JavaClientCodegen(); - codegenConfig.setLibrary("jersey1"); - codegenConfig.setOutputDir(output.getAbsolutePath()); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - - //generate content first time without skipOverwrite flag, so all generated files should be recorded - new DefaultGenerator().opts(clientOptInput).generate(); - final File order = new File(output, MODEL_ORDER_FILE); - assertTrue(order.exists()); - - //change content of one file - changeContent(order); - - //generate content second time without skipOverwrite flag, so changed file should be rewritten - new DefaultGenerator().opts(clientOptInput).generate(); - - assertTrue(!TEST_SKIP_OVERWRITE.equals(FileUtils.readFileToString(order, StandardCharsets.UTF_8))); - - //change content again - changeContent(order); - //delete file - final File pom = new File(output, POM_FILE); - if (pom.exists() && !pom.delete()) { - fail("it doesn't delete"); - } - - //generate content third time with skipOverwrite flag, so changed file should not be rewritten - //and deleted file should be recorded - codegenConfig.setSkipOverwrite(true); - new DefaultGenerator().opts(clientOptInput).generate(); - assertEquals(FileUtils.readFileToString(order, StandardCharsets.UTF_8), TEST_SKIP_OVERWRITE); - // Disabling this check, it's not valid with the DefaultCodegen.writeOptional(...) arg -// assertTrue(pom.exists()); - } - - private boolean containsOverloadedComments(File file, String ...search) throws IOException { - for (String line : Files.readAllLines(file.toPath(), Charset.defaultCharset())) { - if (StringUtils.containsAny(line, search)) { - return true; - } - } - - return false; - } - - @Test - public void testOverloadingTemplateFiles() throws Exception { - final File output = folder.getRoot(); - - final Swagger swagger = new SwaggerParser().read("src/test/resources/petstore.json"); - CodegenConfig codegenConfig = new JavaClientCodegen(); - codegenConfig.setLibrary("jersey2"); - codegenConfig.setOutputDir(output.getAbsolutePath()); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - //generate content first time without specifying an overloaded template file, so the default mustache files are used instead - new DefaultGenerator().opts(clientOptInput).generate(); - - final File order = new File(output, MODEL_ORDER_FILE); - assertTrue(order.exists()); - assertFalse(containsOverloadedComments(order, TEMPLATE_COMMENT, LIBRARY_COMMENT)); - - final File gradle = new File(output, BUILD_GRADLE_FILE); - assertTrue(gradle.exists()); - assertFalse(containsOverloadedComments(gradle, TEMPLATE_COMMENT, LIBRARY_COMMENT)); - - final File apiClient = new File(output, API_CLIENT_FILE); - assertTrue(apiClient.exists()); - assertFalse(containsOverloadedComments(apiClient, TEMPLATE_COMMENT, LIBRARY_COMMENT)); - - codegenConfig.additionalProperties().put(TEMPLATE_DIR, "src/test/resources/2_0/templates/Java"); - //generate content second time while specifying a template folder, so the files from the template are used instead - new DefaultGenerator().opts(clientOptInput).generate(); - - //this file won't contain the library comment because Jersey2 doesn't override the model template - assertTrue(order.exists()); - assertTrue(containsOverloadedComments(order, TEMPLATE_COMMENT)); - - assertTrue(gradle.exists()); - assertTrue(containsOverloadedComments(gradle, LIBRARY_COMMENT)); - - assertTrue(apiClient.exists()); - assertTrue(containsOverloadedComments(apiClient, LIBRARY_COMMENT)); - } - - @Test - public void testGenerateUniqueOperationIds() { - final File output = folder.getRoot(); - - final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/duplicateOperationIds.yaml"); - CodegenConfig codegenConfig = new JavaClientCodegen(); - codegenConfig.setOutputDir(output.getAbsolutePath()); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - - DefaultGenerator generator = new DefaultGenerator(); - generator.opts(clientOptInput); - - Map> paths = generator.processPaths(swagger.getPaths()); - Set opIds = new HashSet(); - for(String path : paths.keySet()) { - List ops = paths.get(path); - for(CodegenOperation op : ops) { - assertFalse(opIds.contains(op.operationId)); - opIds.add(op.operationId); - } - } - } - - @Test - public void testResolveTagsAgainstSwaggerTagsDefinition() { - final File output = folder.getRoot(); - - String spec = - "swagger: '2.0'\n" + - "info:\n" + - " version: 1.0.0\n" + - " title: Swagger Petstore\n" + - "tags:\n" + - " - name: pet\n" + - " description: Everything about your Pets\n" + - " externalDocs:\n" + - " description: Find out more\n" + - " url: 'http://swagger.io'\n" + - " x-vendor-ext: 'tag'\n" + - " - name: store\n" + - " description: Access to Petstore orders\n" + - " - name: user\n" + - " description: Operations about user\n" + - " externalDocs:\n" + - " x-vendor-ext: 'foo'\n" + - "paths:\n" + - " /pet:\n" + - " get:\n" + - " tags:\n" + - " - pet\n" + - " - store\n" + - " - user\n" + - " responses:\n" + - " '200':\n" + - " description: OK"; - - final List expectedTags = new ArrayList(); - expectedTags.add(new Tag().name("pet").description("Everything about your Pets").externalDocs(new ExternalDocs().description("Find out more").url("http://swagger.io"))); - expectedTags.add(new Tag().name("store").description("Access to Petstore orders")); - expectedTags.add(new Tag().name("user").description("Operations about user").externalDocs(new ExternalDocs())); - - expectedTags.get(0).getVendorExtensions().put("x-vendor-ext", "tag"); - expectedTags.get(2).getExternalDocs().getVendorExtensions().put("x-vendor-ext", "foo"); - - final Swagger swagger = new SwaggerParser().readWithInfo(spec).getSwagger(); - CodegenConfig codegenConfig = new JavaClientCodegen(); - codegenConfig.setOutputDir(output.getAbsolutePath()); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - - DefaultGenerator generator = new DefaultGenerator(); - generator.opts(clientOptInput); - - Map> paths = generator.processPaths(swagger.getPaths()); - assertEquals(3, paths.size()); - - List sanitizedTags = Arrays.asList("Pet", "Store", "User"); - for (String tag : sanitizedTags) { - List operations = paths.get(tag); - assertNotNull(operations); - for (CodegenOperation operation : operations) { - assertOperationHasTags(operation, expectedTags); - } - } - } - - @Test - public void testResolveTagsNoSwaggerTagsDefinition() { - final File output = folder.getRoot(); - - String spec = - "swagger: '2.0'\n" + - "info:\n" + - " version: 1.0.0\n" + - " title: Swagger Petstore\n" + - "paths:\n" + - " /pet:\n" + - " get:\n" + - " tags:\n" + - " - pet\n" + - " - store\n" + - " - user\n" + - " responses:\n" + - " '200':\n" + - " description: OK"; - - final List expectedTags = new ArrayList(); - expectedTags.add(new Tag().name("pet")); - expectedTags.add(new Tag().name("store")); - expectedTags.add(new Tag().name("user")); - - final Swagger swagger = new SwaggerParser().readWithInfo(spec).getSwagger(); - CodegenConfig codegenConfig = new JavaClientCodegen(); - codegenConfig.setOutputDir(output.getAbsolutePath()); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - - DefaultGenerator generator = new DefaultGenerator(); - generator.opts(clientOptInput); - - Map> paths = generator.processPaths(swagger.getPaths()); - assertEquals(3, paths.size()); - - List sanitizedTags = Arrays.asList("Pet", "Store", "User"); - for (String tag : sanitizedTags) { - List operations = paths.get(tag); - assertNotNull(operations); - for (CodegenOperation operation : operations) { - assertOperationHasTags(operation, expectedTags); - } - } - } - - @Test - public void testResolveTagsNoTagsDefined() { - final File output = folder.getRoot(); - - String spec = - "swagger: '2.0'\n" + - "info:\n" + - " version: 1.0.0\n" + - " title: Swagger Petstore\n" + - "paths:\n" + - " /pet:\n" + - " get:\n" + - " responses:\n" + - " '200':\n" + - " description: OK"; - - final List expectedTags = new ArrayList(); - expectedTags.add(new Tag().name("default")); - - final Swagger swagger = new SwaggerParser().readWithInfo(spec).getSwagger(); - CodegenConfig codegenConfig = new JavaClientCodegen(); - codegenConfig.setOutputDir(output.getAbsolutePath()); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - - DefaultGenerator generator = new DefaultGenerator(); - generator.opts(clientOptInput); - - Map> paths = generator.processPaths(swagger.getPaths()); - assertEquals(1, paths.size()); - - List sanitizedTags = Collections.singletonList("Default"); - for (String tag : sanitizedTags) { - List operations = paths.get(tag); - assertNotNull(operations); - for (CodegenOperation operation : operations) { - assertOperationHasTags(operation, expectedTags); - } - } - } - - @Test - public void testResolveTagNotDefinedInSwaggerTagsDefinition() { - final File output = folder.getRoot(); - - String spec = - "swagger: '2.0'\n" + - "info:\n" + - " version: 1.0.0\n" + - " title: Swagger Petstore\n" + - "tags:\n" + - " - name: pet\n" + - " description: Everything about your Pets\n" + - "paths:\n" + - " /pet:\n" + - " get:\n" + - " tags:\n" + - " - pet\n" + - " - store\n" + // Not defined above - " - user\n" + // Not defined above - " responses:\n" + - " '200':\n" + - " description: OK"; - - final List expectedTags = new ArrayList(); - expectedTags.add(new Tag().name("pet").description("Everything about your Pets")); - expectedTags.add(new Tag().name("store")); - expectedTags.add(new Tag().name("user")); - - final Swagger swagger = new SwaggerParser().readWithInfo(spec).getSwagger(); - CodegenConfig codegenConfig = new JavaClientCodegen(); - codegenConfig.setOutputDir(output.getAbsolutePath()); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - - DefaultGenerator generator = new DefaultGenerator(); - generator.opts(clientOptInput); - - Map> paths = generator.processPaths(swagger.getPaths()); - assertEquals(3, paths.size()); - - List sanitizedTags = Arrays.asList("Pet", "Store", "User"); - for (String tag : sanitizedTags) { - List operations = paths.get(tag); - assertNotNull(operations); - for (CodegenOperation operation : operations) { - assertOperationHasTags(operation, expectedTags); - } - } - } - - private void assertOperationHasTags(CodegenOperation op, List expectedTags) { - assertNotNull(op.tags); - assertEquals(op.tags.size(), expectedTags.size()); - - for (Tag tag : expectedTags) { - Tag foundTag = null; - - for (Tag opTag : op.tags) { - if (tag.getName().equals(opTag.getName())) { - foundTag = opTag; - break; - } - } - - if (foundTag == null) { - fail("Expected tag '" + tag.getName() + "' was not found on operation " + op.operationId); - } - - assertEquals(tag, foundTag); - if (!tag.getVendorExtensions().isEmpty()) { - assertEquals(tag.getVendorExtensions(), foundTag.getVendorExtensions()); - } - - if (tag.getExternalDocs() != null && !tag.getExternalDocs().getVendorExtensions().isEmpty()) { - assertEquals(tag.getExternalDocs().getVendorExtensions(), foundTag.getExternalDocs().getVendorExtensions()); - } - } - } - - private static void changeContent(File file) throws IOException { - Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), UTF_8)); - out.write(TEST_SKIP_OVERWRITE); - out.close(); - } - - private static CodegenOperation findCodegenOperationByOperationId(Map> paths, String operationId) { - for (List ops : paths.values()) { - for (CodegenOperation co : ops) { - if (operationId.equals(co.operationId)) { - return co; - } - } - } - return null; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java deleted file mode 100644 index 427563ce12c9..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.openapitools.codegen; - -import org.openapitools.codegen.examples.ExampleGenerator; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Xml; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Sets; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; - -@SuppressWarnings("static-method") -public class ExampleGeneratorTest { - - @Test(description = "check handling of recursive models") - public void recursiveModelsTest() { - final String JSON = "application/json"; - final String XML = "application/xml"; - final String nodeType = "Node"; - final RefProperty ref = new RefProperty(nodeType); - final Model node = new ModelImpl().name(nodeType).property("name", new StringProperty()) - .property("parent", ref) - .property("children", new ArrayProperty(ref)) - .property("wrappedChildren", new ArrayProperty(ref).xml(new Xml().wrapped(true))); - final String pairType = "Pair"; - final ModelImpl pair = new ModelImpl().name(pairType); - for (Map.Entry item : ImmutableMap.of("first", "First", "second", "Second").entrySet()) { - final RefProperty property = new RefProperty(nodeType); - property.setXml(new Xml().name(item.getValue())); - pair.property(item.getKey(), property); - - } - final Set types = Sets.newHashSet(); - final List expectedTypes = Arrays.asList(JSON, XML); - - final ExampleGenerator eg = new ExampleGenerator(ImmutableMap.of(nodeType, node, pairType, pair)); - for (Map item : eg.generate(null, expectedTypes, new RefProperty(pairType))) { - final String example = item.get("example"); - final String contentType = item.get("contentType"); - if (XML.equals(contentType)) { - types.add(XML); - Assert.assertEquals(example, "\n" + - " \n" + - " aeiou\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " aeiou\n" + - " \n" + - " \n" + - " \n" + - ""); - } else if (JSON.equals(contentType)) { - types.add(JSON); - // TODO - add JSON validation - Assert.assertNotNull(example); - } - } - - Assert.assertEqualsNoOrder(types.toArray(new String[types.size()]), - expectedTypes.toArray(new String[expectedTypes.size()])); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/InlineModelResolverTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/InlineModelResolverTest.java deleted file mode 100644 index ded3314e8fe1..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/InlineModelResolverTest.java +++ /dev/null @@ -1,992 +0,0 @@ -package org.openapitools.codegen; - -import io.swagger.models.*; -import io.swagger.models.parameters.BodyParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.*; -import io.swagger.util.Json; -import org.testng.annotations.Test; - -import java.util.Map; - -import static org.testng.AssertJUnit.*; - -@SuppressWarnings("static-method") -public class InlineModelResolverTest { - @Test - public void resolveInlineModelTestWithoutTitle() throws Exception { - Swagger swagger = new Swagger(); - - swagger.addDefinition("User", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("address", new ObjectProperty() - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); - - new InlineModelResolver().flatten(swagger); - - ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); - - assertNotNull(user); - assertTrue(user.getProperties().get("address") instanceof RefProperty); - - ModelImpl address = (ModelImpl)swagger.getDefinitions().get("User_address"); - assertNotNull(address); - assertNotNull(address.getProperties().get("city")); - assertNotNull(address.getProperties().get("street")); - } - - @Test - public void resolveInlineModelTestWithTitle() throws Exception { - Swagger swagger = new Swagger(); - - swagger.addDefinition("User", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("address", new ObjectProperty() - .title("UserAddressTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); - - new InlineModelResolver().flatten(swagger); - - ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); - - assertNotNull(user); - assertTrue(user.getProperties().get("address") instanceof RefProperty); - - ModelImpl address = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle"); - assertNotNull(address); - assertNotNull(address.getProperties().get("city")); - assertNotNull(address.getProperties().get("street")); - } - - @Test - public void resolveInlineModel2EqualInnerModels() throws Exception { - Swagger swagger = new Swagger(); - - swagger.addDefinition("User", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("address", new ObjectProperty() - .title("UserAddressTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); - - swagger.addDefinition("AnotherUser", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("lastName", new StringProperty()) - .property("address", new ObjectProperty() - .title("UserAddressTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); - - new InlineModelResolver().flatten(swagger); - - ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); - - assertNotNull(user); - assertTrue(user.getProperties().get("address") instanceof RefProperty); - - ModelImpl address = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle"); - assertNotNull(address); - assertNotNull(address.getProperties().get("city")); - assertNotNull(address.getProperties().get("street")); - ModelImpl duplicateAddress = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle_0"); - assertNull(duplicateAddress); - } - - @Test - public void resolveInlineModel2DifferentInnerModelsWIthSameTitle() throws Exception { - Swagger swagger = new Swagger(); - - swagger.addDefinition("User", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("address", new ObjectProperty() - .title("UserAddressTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); - - swagger.addDefinition("AnotherUser", new ModelImpl() - .name("AnotherUser") - .description("a common user") - .property("name", new StringProperty()) - .property("lastName", new StringProperty()) - .property("address", new ObjectProperty() - .title("UserAddressTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()) - .property("apartment", new StringProperty()))); - - new InlineModelResolver().flatten(swagger); - - ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); - - assertNotNull(user); - assertTrue(user.getProperties().get("address") instanceof RefProperty); - - ModelImpl address = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle"); - assertNotNull(address); - assertNotNull(address.getProperties().get("city")); - assertNotNull(address.getProperties().get("street")); - ModelImpl duplicateAddress = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle_1"); - assertNotNull(duplicateAddress); - assertNotNull(duplicateAddress.getProperties().get("city")); - assertNotNull(duplicateAddress.getProperties().get("street")); - assertNotNull(duplicateAddress.getProperties().get("apartment")); - } - - - @Test - public void testInlineResponseModel() throws Exception { - Swagger swagger = new Swagger(); - - swagger.path("/foo/bar", new Path() - .get(new Operation() - .response(200, new Response() - .description("it works!") - .schema(new ObjectProperty() - .property("name", new StringProperty()).vendorExtension("x-ext", "ext-prop"))))) - .path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") - .schema(new ObjectProperty() - .property("name", new StringProperty()).vendorExtension("x-ext", "ext-prop"))))); - new InlineModelResolver().flatten(swagger); - - Map responses = swagger.getPaths().get("/foo/bar").getGet().getResponses(); - - Response response = responses.get("200"); - assertNotNull(response); - Property schema = response.getSchema(); - assertTrue(schema instanceof RefProperty); - assertEquals(1, schema.getVendorExtensions().size()); - assertEquals("ext-prop", schema.getVendorExtensions().get("x-ext")); - - ModelImpl model = (ModelImpl)swagger.getDefinitions().get("inline_response_200"); - assertTrue(model.getProperties().size() == 1); - assertNotNull(model.getProperties().get("name")); - assertTrue(model.getProperties().get("name") instanceof StringProperty); - } - - - @Test - public void testInlineResponseModelWithTitle() throws Exception { - Swagger swagger = new Swagger(); - - String responseTitle = "GetBarResponse"; - swagger.path("/foo/bar", new Path() - .get(new Operation() - .response(200, new Response() - .description("it works!") - .schema(new ObjectProperty().title(responseTitle) - .property("name", new StringProperty()))))) - .path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") - .schema(new ObjectProperty() - .property("name", new StringProperty()))))); - new InlineModelResolver().flatten(swagger); - - Map responses = swagger.getPaths().get("/foo/bar").getGet().getResponses(); - - Response response = responses.get("200"); - assertNotNull(response); - assertTrue(response.getSchema() instanceof RefProperty); - - ModelImpl model = (ModelImpl)swagger.getDefinitions().get(responseTitle); - assertTrue(model.getProperties().size() == 1); - assertNotNull(model.getProperties().get("name")); - assertTrue(model.getProperties().get("name") instanceof StringProperty); - } - - - @Test - public void resolveInlineArrayModelWithTitle() throws Exception { - Swagger swagger = new Swagger(); - - swagger.addDefinition("User", new ArrayModel() - .items(new ObjectProperty() - .title("InnerUserTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); - - new InlineModelResolver().flatten(swagger); - - Model model = swagger.getDefinitions().get("User"); - assertTrue(model instanceof ArrayModel); - - Model user = swagger.getDefinitions().get("InnerUserTitle"); - assertNotNull(user); - assertEquals("description", user.getDescription()); - } - - @Test - public void resolveInlineArrayModelWithoutTitle() throws Exception { - Swagger swagger = new Swagger(); - - swagger.addDefinition("User", new ArrayModel() - .items(new ObjectProperty() - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); - - new InlineModelResolver().flatten(swagger); - - Model model = swagger.getDefinitions().get("User"); - assertTrue(model instanceof ArrayModel); - - Model user = swagger.getDefinitions().get("User_inner"); - assertNotNull(user); - assertEquals("description", user.getDescription()); - } - - - - - @Test - public void resolveInlineBodyParameter() throws Exception { - Swagger swagger = new Swagger(); - - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ModelImpl() - .property("address", new ObjectProperty() - .property("street", new StringProperty())) - .property("name", new StringProperty()))))); - - new InlineModelResolver().flatten(swagger); - - Operation operation = swagger.getPaths().get("/hello").getGet(); - BodyParameter bp = (BodyParameter)operation.getParameters().get(0); - assertTrue(bp.getSchema() instanceof RefModel); - - Model body = swagger.getDefinitions().get("body"); - assertTrue(body instanceof ModelImpl); - - ModelImpl impl = (ModelImpl) body; - assertNotNull(impl.getProperties().get("address")); - } - - @Test - public void resolveInlineBodyParameterWithRequired() throws Exception { - Swagger swagger = new Swagger(); - - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ModelImpl() - .property("address", new ObjectProperty() - .property("street", new StringProperty() - .required(true)) - .required(true)) - .property("name", new StringProperty()))))); - - new InlineModelResolver().flatten(swagger); - - Operation operation = swagger.getPaths().get("/hello").getGet(); - BodyParameter bp = (BodyParameter)operation.getParameters().get(0); - assertTrue(bp.getSchema() instanceof RefModel); - - Model body = swagger.getDefinitions().get("body"); - assertTrue(body instanceof ModelImpl); - - ModelImpl impl = (ModelImpl) body; - assertNotNull(impl.getProperties().get("address")); - - Property addressProperty = impl.getProperties().get("address"); - assertTrue(addressProperty instanceof RefProperty); - assertTrue(addressProperty.getRequired()); - - Model helloAddress = swagger.getDefinitions().get("hello_address"); - assertTrue(helloAddress instanceof ModelImpl); - - ModelImpl addressImpl = (ModelImpl) helloAddress; - assertNotNull(addressImpl); - - Property streetProperty = addressImpl.getProperties().get("street"); - assertTrue(streetProperty instanceof StringProperty); - assertTrue(streetProperty.getRequired()); - } - - @Test - public void resolveInlineBodyParameterWithTitle() throws Exception { - Swagger swagger = new Swagger(); - - ModelImpl addressModelItem = new ModelImpl(); - String addressModelName = "DetailedAddress"; - addressModelItem.setTitle(addressModelName); - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(addressModelItem - .property("address", new ObjectProperty() - .property("street", new StringProperty())) - .property("name", new StringProperty()))))); - - new InlineModelResolver().flatten(swagger); - - Operation operation = swagger.getPaths().get("/hello").getGet(); - BodyParameter bp = (BodyParameter)operation.getParameters().get(0); - assertTrue(bp.getSchema() instanceof RefModel); - - Model body = swagger.getDefinitions().get(addressModelName); - assertTrue(body instanceof ModelImpl); - - ModelImpl impl = (ModelImpl) body; - assertNotNull(impl.getProperties().get("address")); - } - - @Test - public void notResolveNonModelBodyParameter() throws Exception { - Swagger swagger = new Swagger(); - - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ModelImpl() - .type("string") - .format("binary"))))); - - new InlineModelResolver().flatten(swagger); - - Operation operation = swagger.getPaths().get("/hello").getGet(); - BodyParameter bp = (BodyParameter)operation.getParameters().get(0); - assertTrue(bp.getSchema() instanceof ModelImpl); - ModelImpl m = (ModelImpl) bp.getSchema(); - assertEquals("string", m.getType()); - assertEquals("binary", m.getFormat()); - } - - @Test - public void resolveInlineArrayBodyParameter() throws Exception { - Swagger swagger = new Swagger(); - - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ArrayModel() - .items(new ObjectProperty() - .property("address", new ObjectProperty() - .property("street", new StringProperty()))))))); - - new InlineModelResolver().flatten(swagger); - - Parameter param = swagger.getPaths().get("/hello").getGet().getParameters().get(0); - assertTrue(param instanceof BodyParameter); - - BodyParameter bp = (BodyParameter) param; - Model schema = bp.getSchema(); - - assertTrue(schema instanceof ArrayModel); - - ArrayModel am = (ArrayModel) schema; - Property inner = am.getItems(); - assertTrue(inner instanceof RefProperty); - - RefProperty rp = (RefProperty) inner; - - assertEquals(rp.getType(), "ref"); - assertEquals(rp.get$ref(), "#/definitions/body"); - assertEquals(rp.getSimpleRef(), "body"); - - Model inline = swagger.getDefinitions().get("body"); - assertNotNull(inline); - assertTrue(inline instanceof ModelImpl); - ModelImpl impl = (ModelImpl) inline; - RefProperty rpAddress = (RefProperty) impl.getProperties().get("address"); - assertNotNull(rpAddress); - assertEquals(rpAddress.getType(), "ref"); - assertEquals(rpAddress.get$ref(), "#/definitions/hello_address"); - assertEquals(rpAddress.getSimpleRef(), "hello_address"); - - Model inlineProp = swagger.getDefinitions().get("hello_address"); - assertNotNull(inlineProp); - assertTrue(inlineProp instanceof ModelImpl); - ModelImpl implProp = (ModelImpl) inlineProp; - assertNotNull(implProp.getProperties().get("street")); - assertTrue(implProp.getProperties().get("street") instanceof StringProperty); - } - - @Test - public void resolveInlineArrayResponse() throws Exception { - Swagger swagger = new Swagger(); - - ArrayProperty schema = new ArrayProperty() - .items(new ObjectProperty() - .property("name", new StringProperty()) - .vendorExtension("x-ext", "ext-items")) - .vendorExtension("x-ext", "ext-prop"); - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") - .schema(schema)))); - - new InlineModelResolver().flatten(swagger); - - Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); - assertNotNull(response); - - assertNotNull(response.getSchema()); - Property responseProperty = response.getSchema(); - - // no need to flatten more - assertTrue(responseProperty instanceof ArrayProperty); - - ArrayProperty ap = (ArrayProperty) responseProperty; - assertEquals(1, ap.getVendorExtensions().size()); - assertEquals("ext-prop", ap.getVendorExtensions().get("x-ext")); - - Property p = ap.getItems(); - - assertNotNull(p); - - RefProperty rp = (RefProperty) p; - assertEquals(rp.getType(), "ref"); - assertEquals(rp.get$ref(), "#/definitions/inline_response_200"); - assertEquals(rp.getSimpleRef(), "inline_response_200"); - assertEquals(1, rp.getVendorExtensions().size()); - assertEquals("ext-items", rp.getVendorExtensions().get("x-ext")); - - Model inline = swagger.getDefinitions().get("inline_response_200"); - assertNotNull(inline); - assertTrue(inline instanceof ModelImpl); - ModelImpl impl = (ModelImpl) inline; - assertNotNull(impl.getProperties().get("name")); - assertTrue(impl.getProperties().get("name") instanceof StringProperty); - } - - @Test - public void resolveInlineArrayResponseWithTitle() throws Exception { - Swagger swagger = new Swagger(); - - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") - .schema(new ArrayProperty() - .items(new ObjectProperty() - .title("FooBar") - .property("name", new StringProperty())))))); - - new InlineModelResolver().flatten(swagger); - - Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); - assertNotNull(response); - - assertNotNull(response.getSchema()); - Property responseProperty = response.getSchema(); - - // no need to flatten more - assertTrue(responseProperty instanceof ArrayProperty); - - ArrayProperty ap = (ArrayProperty) responseProperty; - Property p = ap.getItems(); - - assertNotNull(p); - - RefProperty rp = (RefProperty) p; - assertEquals(rp.getType(), "ref"); - assertEquals(rp.get$ref(), "#/definitions/"+ "FooBar"); - assertEquals(rp.getSimpleRef(), "FooBar"); - - Model inline = swagger.getDefinitions().get("FooBar"); - assertNotNull(inline); - assertTrue(inline instanceof ModelImpl); - ModelImpl impl = (ModelImpl) inline; - assertNotNull(impl.getProperties().get("name")); - assertTrue(impl.getProperties().get("name") instanceof StringProperty); - } - - @Test - public void testInlineMapResponse() throws Exception { - Swagger swagger = new Swagger(); - - MapProperty schema = new MapProperty(); - schema.setAdditionalProperties(new StringProperty()); - schema.setVendorExtension("x-ext", "ext-prop"); - - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") - .schema(schema)))); - new InlineModelResolver().flatten(swagger); - Json.prettyPrint(swagger); - - Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); - - Property property = response.getSchema(); - assertTrue(property instanceof MapProperty); - assertTrue(swagger.getDefinitions().size() == 0); - assertEquals(1, property.getVendorExtensions().size()); - assertEquals("ext-prop", property.getVendorExtensions().get("x-ext")); - } - - @Test - public void testInlineMapResponseWithObjectProperty() throws Exception { - Swagger swagger = new Swagger(); - - MapProperty schema = new MapProperty(); - schema.setAdditionalProperties(new ObjectProperty() - .property("name", new StringProperty())); - schema.setVendorExtension("x-ext", "ext-prop"); - - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") - .schema(schema)))); - new InlineModelResolver().flatten(swagger); - - Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); - Property property = response.getSchema(); - assertTrue(property instanceof MapProperty); - assertEquals(1, property.getVendorExtensions().size()); - assertEquals("ext-prop", property.getVendorExtensions().get("x-ext")); - assertTrue(swagger.getDefinitions().size() == 1); - - Model inline = swagger.getDefinitions().get("inline_response_200"); - assertTrue(inline instanceof ModelImpl); - ModelImpl impl = (ModelImpl) inline; - assertNotNull(impl.getProperties().get("name")); - assertTrue(impl.getProperties().get("name") instanceof StringProperty); - } - - @Test - public void testArrayResponse() { - Swagger swagger = new Swagger(); - - ArrayProperty schema = new ArrayProperty(); - schema.setItems(new ObjectProperty() - .property("name", new StringProperty())); - - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") - .schema(schema)))); - new InlineModelResolver().flatten(swagger); - - Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); - assertTrue(response.getSchema() instanceof ArrayProperty); - - ArrayProperty am = (ArrayProperty) response.getSchema(); - Property items = am.getItems(); - assertTrue(items instanceof RefProperty); - RefProperty rp = (RefProperty) items; - assertEquals(rp.getType(), "ref"); - assertEquals(rp.get$ref(), "#/definitions/inline_response_200"); - assertEquals(rp.getSimpleRef(), "inline_response_200"); - - Model inline = swagger.getDefinitions().get("inline_response_200"); - assertTrue(inline instanceof ModelImpl); - ModelImpl impl = (ModelImpl) inline; - assertNotNull(impl.getProperties().get("name")); - assertTrue(impl.getProperties().get("name") instanceof StringProperty); - } - - @Test - public void testBasicInput() { - Swagger swagger = new Swagger(); - - ModelImpl user = new ModelImpl() - .property("name", new StringProperty()); - - swagger.path("/foo/baz", new Path() - .post(new Operation() - .parameter(new BodyParameter() - .name("myBody") - .schema(new RefModel("User"))))); - - swagger.addDefinition("User", user); - - new InlineModelResolver().flatten(swagger); - - Json.prettyPrint(swagger); - } - - @Test - public void testArbitraryObjectBodyParam() { - Swagger swagger = new Swagger(); - - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ModelImpl())))); - - new InlineModelResolver().flatten(swagger); - - Operation operation = swagger.getPaths().get("/hello").getGet(); - BodyParameter bp = (BodyParameter)operation.getParameters().get(0); - assertTrue(bp.getSchema() instanceof ModelImpl); - ModelImpl m = (ModelImpl) bp.getSchema(); - assertNull(m.getType()); - } - - @Test - public void testArbitraryObjectBodyParamInline() { - Swagger swagger = new Swagger(); - - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ModelImpl() - .property("arbitrary", new ObjectProperty()))))); - - new InlineModelResolver().flatten(swagger); - - Operation operation = swagger.getPaths().get("/hello").getGet(); - BodyParameter bp = (BodyParameter)operation.getParameters().get(0); - assertTrue(bp.getSchema() instanceof RefModel); - - Model body = swagger.getDefinitions().get("body"); - assertTrue(body instanceof ModelImpl); - - ModelImpl impl = (ModelImpl) body; - Property p = impl.getProperties().get("arbitrary"); - assertNotNull(p); - assertTrue(p instanceof ObjectProperty); - } - - @Test - public void testArbitraryObjectBodyParamWithArray() { - Swagger swagger = new Swagger(); - - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ArrayModel() - .items(new ObjectProperty()))))); - - new InlineModelResolver().flatten(swagger); - - Parameter param = swagger.getPaths().get("/hello").getGet().getParameters().get(0); - assertTrue(param instanceof BodyParameter); - - BodyParameter bp = (BodyParameter) param; - Model schema = bp.getSchema(); - - assertTrue(schema instanceof ArrayModel); - - ArrayModel am = (ArrayModel) schema; - Property inner = am.getItems(); - assertTrue(inner instanceof ObjectProperty); - - ObjectProperty op = (ObjectProperty) inner; - assertNotNull(op); - assertNull(op.getProperties()); - } - - @Test - public void testArbitraryObjectBodyParamArrayInline() { - Swagger swagger = new Swagger(); - - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ArrayModel() - .items(new ObjectProperty() - .property("arbitrary", new ObjectProperty())))))); - - new InlineModelResolver().flatten(swagger); - - Parameter param = swagger.getPaths().get("/hello").getGet().getParameters().get(0); - assertTrue(param instanceof BodyParameter); - - BodyParameter bp = (BodyParameter) param; - Model schema = bp.getSchema(); - - assertTrue(schema instanceof ArrayModel); - - ArrayModel am = (ArrayModel) schema; - Property inner = am.getItems(); - assertTrue(inner instanceof RefProperty); - - RefProperty rp = (RefProperty) inner; - - assertEquals(rp.getType(), "ref"); - assertEquals(rp.get$ref(), "#/definitions/body"); - assertEquals(rp.getSimpleRef(), "body"); - - Model inline = swagger.getDefinitions().get("body"); - assertNotNull(inline); - assertTrue(inline instanceof ModelImpl); - ModelImpl impl = (ModelImpl) inline; - Property p = impl.getProperties().get("arbitrary"); - assertNotNull(p); - assertTrue(p instanceof ObjectProperty); - } - - @Test - public void testArbitraryObjectResponse() { - Swagger swagger = new Swagger(); - - swagger.path("/foo/bar", new Path() - .get(new Operation() - .response(200, new Response() - .description("it works!") - .schema(new ObjectProperty())))); - new InlineModelResolver().flatten(swagger); - - Map responses = swagger.getPaths().get("/foo/bar").getGet().getResponses(); - - Response response = responses.get("200"); - assertNotNull(response); - assertTrue(response.getSchema() instanceof ObjectProperty); - ObjectProperty op = (ObjectProperty) response.getSchema(); - assertNull(op.getProperties()); - } - - @Test - public void testArbitraryObjectResponseArray() { - Swagger swagger = new Swagger(); - - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .description("it works!") - .schema(new ArrayProperty() - .items(new ObjectProperty()))))); - new InlineModelResolver().flatten(swagger); - - Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); - assertTrue(response.getSchema() instanceof ArrayProperty); - - ArrayProperty am = (ArrayProperty) response.getSchema(); - Property items = am.getItems(); - assertTrue(items instanceof ObjectProperty); - ObjectProperty op = (ObjectProperty) items; - assertNull(op.getProperties()); - } - - @Test - public void testArbitraryObjectResponseArrayInline() { - Swagger swagger = new Swagger(); - - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") - .schema(new ArrayProperty() - .items(new ObjectProperty() - .property("arbitrary", new ObjectProperty())))))); - - new InlineModelResolver().flatten(swagger); - - Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); - assertNotNull(response); - - assertNotNull(response.getSchema()); - Property responseProperty = response.getSchema(); - assertTrue(responseProperty instanceof ArrayProperty); - - ArrayProperty ap = (ArrayProperty) responseProperty; - Property p = ap.getItems(); - assertNotNull(p); - - RefProperty rp = (RefProperty) p; - assertEquals(rp.getType(), "ref"); - assertEquals(rp.get$ref(), "#/definitions/inline_response_200"); - assertEquals(rp.getSimpleRef(), "inline_response_200"); - - Model inline = swagger.getDefinitions().get("inline_response_200"); - assertNotNull(inline); - assertTrue(inline instanceof ModelImpl); - ModelImpl impl = (ModelImpl) inline; - Property inlineProp = impl.getProperties().get("arbitrary"); - assertNotNull(inlineProp); - assertTrue(inlineProp instanceof ObjectProperty); - ObjectProperty op = (ObjectProperty) inlineProp; - assertNull(op.getProperties()); - } - - @Test - public void testArbitraryObjectResponseMapInline() { - Swagger swagger = new Swagger(); - - MapProperty schema = new MapProperty(); - schema.setAdditionalProperties(new ObjectProperty()); - - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .description("it works!") - .schema(schema)))); - new InlineModelResolver().flatten(swagger); - - Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); - - Property property = response.getSchema(); - assertTrue(property instanceof MapProperty); - assertTrue(swagger.getDefinitions().size() == 0); - Property inlineProp = ((MapProperty) property).getAdditionalProperties(); - assertTrue(inlineProp instanceof ObjectProperty); - ObjectProperty op = (ObjectProperty) inlineProp; - assertNull(op.getProperties()); - } - - @Test - public void testArbitraryObjectModelInline() { - Swagger swagger = new Swagger(); - - swagger.addDefinition("User", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("arbitrary", new ObjectProperty() - .title("title") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name"))); - - new InlineModelResolver().flatten(swagger); - - ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); - assertNotNull(user); - Property inlineProp = user.getProperties().get("arbitrary"); - assertTrue(inlineProp instanceof ObjectProperty); - ObjectProperty op = (ObjectProperty) inlineProp; - assertNull(op.getProperties()); - } - - @Test - public void testArbitraryObjectModelWithArrayInlineWithoutTitle() { - Swagger swagger = new Swagger(); - - swagger.addDefinition("User", new ArrayModel() - .items(new ObjectProperty() - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("arbitrary", new ObjectProperty()))); - - new InlineModelResolver().flatten(swagger); - - Model model = swagger.getDefinitions().get("User"); - assertTrue(model instanceof ArrayModel); - ArrayModel am = (ArrayModel) model; - Property inner = am.getItems(); - assertTrue(inner instanceof RefProperty); - - ModelImpl userInner = (ModelImpl)swagger.getDefinitions().get("User_inner"); - assertNotNull(userInner); - Property inlineProp = userInner.getProperties().get("arbitrary"); - assertTrue(inlineProp instanceof ObjectProperty); - ObjectProperty op = (ObjectProperty) inlineProp; - assertNull(op.getProperties()); - } - - @Test - public void testArbitraryObjectModelWithArrayInlineWithTitle() { - Swagger swagger = new Swagger(); - - swagger.addDefinition("User", new ArrayModel() - .items(new ObjectProperty() - .title("InnerUserTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("arbitrary", new ObjectProperty()))); - - new InlineModelResolver().flatten(swagger); - - Model model = swagger.getDefinitions().get("User"); - assertTrue(model instanceof ArrayModel); - ArrayModel am = (ArrayModel) model; - Property inner = am.getItems(); - assertTrue(inner instanceof RefProperty); - - ModelImpl userInner = (ModelImpl)swagger.getDefinitions().get("InnerUserTitle"); - assertNotNull(userInner); - Property inlineProp = userInner.getProperties().get("arbitrary"); - assertTrue(inlineProp instanceof ObjectProperty); - ObjectProperty op = (ObjectProperty) inlineProp; - assertNull(op.getProperties()); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/SwaggerMigratorTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/SwaggerMigratorTest.java deleted file mode 100644 index 4c08a5f739b9..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/SwaggerMigratorTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.openapitools.codegen; - -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; - -import org.testng.annotations.Test; - -@SuppressWarnings("static-method") -public class SwaggerMigratorTest { - - @Test(description = "read a 1.2 spec") - public void swaggerMigratorTest() { - final SwaggerParser loader = new SwaggerParser(); - final Swagger swagger = loader.read("src/test/resources/1_2/petstore-1.2/api-docs"); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientCodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientCodegenTest.java deleted file mode 100644 index 98b91764e13a..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientCodegenTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.openapitools.codegen.akkascala; - -import org.openapitools.codegen.SupportingFile; -import org.openapitools.codegen.languages.AkkaScalaClientCodegen; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertThat; - -public class AkkaScalaClientCodegenTest { - - private AkkaScalaClientCodegen akkaScalaClientCodegen; - - @Before - public void setup() { - this.akkaScalaClientCodegen = new AkkaScalaClientCodegen(); - } - - @Test - public void shouldGenerateReadmeFile() { - List supportingFiles = this.akkaScalaClientCodegen.supportingFiles(); - - assertThat(supportingFiles.contains(new SupportingFile("README.mustache", "", "README.md")), is(equalTo(true))); - assertThat(supportingFiles.contains(new SupportingFile("build.sbt.mustache", "", "build.sbt")), is(equalTo(true))); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java deleted file mode 100644 index 48a29c419d3f..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.openapitools.codegen.akkascala; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.AkkaScalaClientCodegen; -import org.openapitools.codegen.options.AkkaScalaClientOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class AkkaScalaClientOptionsTest extends AbstractOptionsTest { - - @Tested - private AkkaScalaClientCodegen clientCodegen; - - public AkkaScalaClientOptionsTest() { - super(new AkkaScalaClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(AkkaScalaClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(AkkaScalaClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AkkaScalaClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setSourceFolder(AkkaScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java deleted file mode 100644 index 4557ca8e7fd1..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.openapitools.codegen.android; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.AndroidClientCodegen; -import org.openapitools.codegen.options.AndroidClientOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class AndroidClientOptionsTest extends AbstractOptionsTest { - - @Tested - private AndroidClientCodegen clientCodegen; - - public AndroidClientOptionsTest() { - super(new AndroidClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(AndroidClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(AndroidClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AndroidClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(AndroidClientOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(AndroidClientOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(AndroidClientOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(AndroidClientOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(AndroidClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setUseAndroidMavenGradlePlugin(Boolean.valueOf(AndroidClientOptionsProvider.ANDROID_MAVEN_GRADLE_PLUGIN_VALUE)); - times = 1; - clientCodegen.setAndroidGradleVersion(AndroidClientOptionsProvider.ANDROID_GRADLE_VERSION_VALUE); - times = 1; - clientCodegen.setAndroidSdkVersion(AndroidClientOptionsProvider.ANDROID_SDK_VERSION_VALUE); - times = 1; - clientCodegen.setAndroidBuildToolsVersion(AndroidClientOptionsProvider.ANDROID_BUILD_TOOLS_VERSION_VALUE); - times = 1; - clientCodegen.setLibrary(AndroidClientOptionsProvider.LIBRARY_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(AndroidClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setAllowUnicodeIdentifiers(Boolean.valueOf(AndroidClientOptionsProvider.ALLOW_UNICODE_IDENTIFIERS_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/apex/ApexModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/apex/ApexModelTest.java deleted file mode 100644 index ec2471dd9b29..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/apex/ApexModelTest.java +++ /dev/null @@ -1,875 +0,0 @@ -package org.openapitools.codegen.apex; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.languages.ApexClientCodegen; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.*; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.List; - -@SuppressWarnings("static-method") -public class ApexModelTest { - - @Test(description = "convert a simple apex model with provided examples") - public void examplesProvidedTest() { - BaseIntegerProperty baseIntProp = new BaseIntegerProperty(); - baseIntProp.setExample(5); - - PasswordProperty passwordProp = new PasswordProperty(); - passwordProp.setExample("password"); - - UUIDProperty uuidProp = new UUIDProperty(); - uuidProp.setExample("793574b2-3a8e-4f6c-bfa5-c6929dc29f8a"); - - final Model model = new ModelImpl() - .property("boolProp", new BooleanProperty().example(false)) - .property("dateProp", new DateProperty().example("1985-04-12")) - .property("dateTimeProp", new DateTimeProperty().example("1985-04-12T23:20:50.52Z")) - .property("decimalProp", new DecimalProperty().example("19.99")) - .property("doubleProp", new DoubleProperty().example(2.95)) - .property("emailProp", new EmailProperty().example("info@example.com")) - .property("floatProp", new FloatProperty().example(3.49f)) - .property("intProp", new IntegerProperty().example(10)) - .property("longProp", new LongProperty().example(100000L)) - .property("stringProp", new StringProperty().example("foo")) - .property("baseIntProp", baseIntProp) - .property("passwordProp", passwordProp) - .property("uuidProp", uuidProp); - - final ApexClientCodegen codegen = new ApexClientCodegen(); - codegen.setClassPrefix("Prefix"); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "PrefixSample"); - Assert.assertEquals(cm.vars.size(), 13); - - final List vars = cm.vars; - - final CodegenProperty property1 = vars.get(0); - Assert.assertEquals(property1.name, "boolProp"); - Assert.assertEquals(property1.baseName, "boolProp"); - Assert.assertEquals(property1.datatype, "Boolean"); - Assert.assertEquals(property1.baseType, "Boolean"); - Assert.assertEquals(property1.example, "false"); - Assert.assertNull(property1.defaultValue); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.isPrimitiveType); - Assert.assertTrue(property1.isNotContainer); - Assert.assertTrue(property1.isBoolean); - - final CodegenProperty property2 = vars.get(1); - Assert.assertEquals(property2.name, "dateProp"); - Assert.assertEquals(property2.baseName, "dateProp"); - Assert.assertEquals(property2.datatype, "Date"); - Assert.assertEquals(property2.baseType, "Date"); - Assert.assertEquals(property2.example, "Date.newInstance(1985, 4, 12)"); - Assert.assertNull(property2.defaultValue); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.isPrimitiveType); - Assert.assertTrue(property2.isNotContainer); - Assert.assertTrue(property2.isDate); - - final CodegenProperty property3 = vars.get(2); - Assert.assertEquals(property3.name, "dateTimeProp"); - Assert.assertEquals(property3.baseName, "dateTimeProp"); - Assert.assertEquals(property3.datatype, "Datetime"); - Assert.assertEquals(property3.baseType, "Datetime"); - Assert.assertEquals(property3.example, "Datetime.newInstanceGmt(1985, 4, 12, 23, 20, 50)"); - Assert.assertNull(property3.defaultValue); - Assert.assertTrue(property3.hasMore); - Assert.assertTrue(property3.isPrimitiveType); - Assert.assertTrue(property3.isNotContainer); - Assert.assertTrue(property3.isDateTime); - - final CodegenProperty property4 = vars.get(3); - Assert.assertEquals(property4.name, "decimalProp"); - Assert.assertEquals(property4.baseName, "decimalProp"); - Assert.assertEquals(property4.datatype, "Double"); - Assert.assertEquals(property4.baseType, "Double"); - Assert.assertEquals(property4.example, "19.99"); - Assert.assertNull(property4.defaultValue); - Assert.assertTrue(property4.hasMore); - Assert.assertTrue(property4.isPrimitiveType); - Assert.assertTrue(property4.isNotContainer); - - final CodegenProperty property5 = vars.get(4); - Assert.assertEquals(property5.name, "doubleProp"); - Assert.assertEquals(property5.baseName, "doubleProp"); - Assert.assertEquals(property5.datatype, "Double"); - Assert.assertEquals(property5.baseType, "Double"); - Assert.assertEquals(property5.example, "2.95"); - Assert.assertNull(property5.defaultValue); - Assert.assertTrue(property5.hasMore); - Assert.assertTrue(property5.isPrimitiveType); - Assert.assertTrue(property5.isNotContainer); - Assert.assertTrue(property5.isDouble); - - final CodegenProperty property6 = vars.get(5); - Assert.assertEquals(property6.name, "emailProp"); - Assert.assertEquals(property6.baseName, "emailProp"); - Assert.assertEquals(property6.datatype, "String"); - Assert.assertEquals(property6.baseType, "String"); - Assert.assertEquals(property6.example, "'info@example.com'"); - Assert.assertNull(property6.defaultValue); - Assert.assertTrue(property6.hasMore); - Assert.assertTrue(property6.isPrimitiveType); - Assert.assertTrue(property6.isNotContainer); - Assert.assertTrue(property6.isString); - - final CodegenProperty property7 = vars.get(6); - Assert.assertEquals(property7.name, "floatProp"); - Assert.assertEquals(property7.baseName, "floatProp"); - Assert.assertEquals(property7.datatype, "Double"); - Assert.assertEquals(property7.baseType, "Double"); - Assert.assertEquals(property7.example, "3.49"); - Assert.assertNull(property7.defaultValue); - Assert.assertTrue(property7.hasMore); - Assert.assertTrue(property7.isPrimitiveType); - Assert.assertTrue(property7.isNotContainer); - Assert.assertTrue(property7.isFloat); - - final CodegenProperty property8 = vars.get(7); - Assert.assertEquals(property8.name, "intProp"); - Assert.assertEquals(property8.baseName, "intProp"); - Assert.assertEquals(property8.datatype, "Integer"); - Assert.assertEquals(property8.baseType, "Integer"); - Assert.assertEquals(property8.example, "10"); - Assert.assertNull(property8.defaultValue); - Assert.assertTrue(property8.hasMore); - Assert.assertTrue(property8.isPrimitiveType); - Assert.assertTrue(property8.isNotContainer); - Assert.assertTrue(property8.isInteger); - - final CodegenProperty property9 = vars.get(8); - Assert.assertEquals(property9.name, "longProp"); - Assert.assertEquals(property9.baseName, "longProp"); - Assert.assertEquals(property9.datatype, "Long"); - Assert.assertEquals(property9.baseType, "Long"); - Assert.assertEquals(property9.example, "100000L"); - Assert.assertNull(property9.defaultValue); - Assert.assertTrue(property9.hasMore); - Assert.assertTrue(property9.isPrimitiveType); - Assert.assertTrue(property9.isNotContainer); - Assert.assertTrue(property9.isLong); - - final CodegenProperty property10 = vars.get(9); - Assert.assertEquals(property10.name, "stringProp"); - Assert.assertEquals(property10.baseName, "stringProp"); - Assert.assertEquals(property10.datatype, "String"); - Assert.assertEquals(property10.baseType, "String"); - Assert.assertEquals(property10.example, "'foo'"); - Assert.assertNull(property10.defaultValue); - Assert.assertTrue(property10.hasMore); - Assert.assertTrue(property10.isPrimitiveType); - Assert.assertTrue(property10.isNotContainer); - Assert.assertTrue(property10.isString); - - final CodegenProperty property11 = vars.get(10); - Assert.assertEquals(property11.name, "baseIntProp"); - Assert.assertEquals(property11.baseName, "baseIntProp"); - Assert.assertEquals(property11.datatype, "Integer"); - Assert.assertEquals(property11.baseType, "Integer"); - Assert.assertEquals(property11.example, "5"); - Assert.assertNull(property11.defaultValue); - Assert.assertTrue(property11.hasMore); - Assert.assertTrue(property11.isPrimitiveType); - Assert.assertTrue(property11.isNotContainer); - Assert.assertTrue(property11.isInteger); - - final CodegenProperty property12 = vars.get(11); - Assert.assertEquals(property12.name, "passwordProp"); - Assert.assertEquals(property12.baseName, "passwordProp"); - Assert.assertEquals(property12.datatype, "String"); - Assert.assertEquals(property12.baseType, "String"); - Assert.assertEquals(property12.example, "'password'"); - Assert.assertNull(property12.defaultValue); - Assert.assertTrue(property12.hasMore); - Assert.assertTrue(property12.isPrimitiveType); - Assert.assertTrue(property12.isNotContainer); - - final CodegenProperty property13 = vars.get(12); - Assert.assertEquals(property13.name, "uuidProp"); - Assert.assertEquals(property13.baseName, "uuidProp"); - Assert.assertEquals(property13.datatype, "String"); - Assert.assertEquals(property13.baseType, "String"); - Assert.assertEquals(property13.example, "'793574b2-3a8e-4f6c-bfa5-c6929dc29f8a'"); - Assert.assertNull(property13.defaultValue); - Assert.assertFalse(property13.hasMore); - Assert.assertTrue(property13.isPrimitiveType); - Assert.assertTrue(property13.isNotContainer); - } - - @Test(description = "convert a simple apex model with default examples") - public void defaultExamplesTest() { - final Model model = new ModelImpl() - .property("boolProp", new BooleanProperty()) - .property("dateProp", new DateProperty()) - .property("dateTimeProp", new DateTimeProperty()) - .property("decimalProp", new DecimalProperty()) - .property("doubleProp", new DoubleProperty()) - .property("emailProp", new EmailProperty()) - .property("floatProp", new FloatProperty()) - .property("intProp", new IntegerProperty()) - .property("longProp", new LongProperty()) - .property("stringProp", new StringProperty()) - .property("baseIntProp", new BaseIntegerProperty()) - .property("passwordProp", new PasswordProperty()) - .property("uuidProp", new UUIDProperty()) - .property("byteArrProp", new ByteArrayProperty()) - .property("binaryProp", new BinaryProperty()); - - final ApexClientCodegen codegen = new ApexClientCodegen(); - codegen.setClassPrefix("Prefix"); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "PrefixSample"); - Assert.assertEquals(cm.vars.size(), 15); - - final List vars = cm.vars; - - final CodegenProperty property1 = vars.get(0); - Assert.assertEquals(property1.name, "boolProp"); - Assert.assertEquals(property1.baseName, "boolProp"); - Assert.assertEquals(property1.datatype, "Boolean"); - Assert.assertEquals(property1.baseType, "Boolean"); - Assert.assertEquals(property1.example, "true"); - Assert.assertNull(property1.defaultValue); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.isPrimitiveType); - Assert.assertTrue(property1.isNotContainer); - Assert.assertTrue(property1.isBoolean); - - final CodegenProperty property2 = vars.get(1); - Assert.assertEquals(property2.name, "dateProp"); - Assert.assertEquals(property2.baseName, "dateProp"); - Assert.assertEquals(property2.datatype, "Date"); - Assert.assertEquals(property2.baseType, "Date"); - Assert.assertEquals(property2.example, "Date.newInstance(2000, 1, 23)"); - Assert.assertNull(property2.defaultValue); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.isPrimitiveType); - Assert.assertTrue(property2.isNotContainer); - Assert.assertTrue(property2.isDate); - - final CodegenProperty property3 = vars.get(2); - Assert.assertEquals(property3.name, "dateTimeProp"); - Assert.assertEquals(property3.baseName, "dateTimeProp"); - Assert.assertEquals(property3.datatype, "Datetime"); - Assert.assertEquals(property3.baseType, "Datetime"); - Assert.assertEquals(property3.example, "Datetime.newInstanceGmt(2000, 1, 23, 4, 56, 7)"); - Assert.assertNull(property3.defaultValue); - Assert.assertTrue(property3.hasMore); - Assert.assertTrue(property3.isPrimitiveType); - Assert.assertTrue(property3.isNotContainer); - Assert.assertTrue(property3.isDateTime); - - final CodegenProperty property4 = vars.get(3); - Assert.assertEquals(property4.name, "decimalProp"); - Assert.assertEquals(property4.baseName, "decimalProp"); - Assert.assertEquals(property4.datatype, "Double"); - Assert.assertEquals(property4.baseType, "Double"); - Assert.assertEquals(property4.example, "1.3579"); - Assert.assertNull(property4.defaultValue); - Assert.assertTrue(property4.hasMore); - Assert.assertTrue(property4.isPrimitiveType); - Assert.assertTrue(property4.isNotContainer); - - final CodegenProperty property5 = vars.get(4); - Assert.assertEquals(property5.name, "doubleProp"); - Assert.assertEquals(property5.baseName, "doubleProp"); - Assert.assertEquals(property5.datatype, "Double"); - Assert.assertEquals(property5.baseType, "Double"); - Assert.assertEquals(property5.example, "1.3579"); - Assert.assertNull(property5.defaultValue); - Assert.assertTrue(property5.hasMore); - Assert.assertTrue(property5.isPrimitiveType); - Assert.assertTrue(property5.isNotContainer); - Assert.assertTrue(property5.isDouble); - - final CodegenProperty property6 = vars.get(5); - Assert.assertEquals(property6.name, "emailProp"); - Assert.assertEquals(property6.baseName, "emailProp"); - Assert.assertEquals(property6.datatype, "String"); - Assert.assertEquals(property6.baseType, "String"); - Assert.assertEquals(property6.example, "'example@example.com'"); - Assert.assertNull(property6.defaultValue); - Assert.assertTrue(property6.hasMore); - Assert.assertTrue(property6.isPrimitiveType); - Assert.assertTrue(property6.isNotContainer); - Assert.assertTrue(property6.isString); - - final CodegenProperty property7 = vars.get(6); - Assert.assertEquals(property7.name, "floatProp"); - Assert.assertEquals(property7.baseName, "floatProp"); - Assert.assertEquals(property7.datatype, "Double"); - Assert.assertEquals(property7.baseType, "Double"); - Assert.assertEquals(property7.example, "1.3579"); - Assert.assertNull(property7.defaultValue); - Assert.assertTrue(property7.hasMore); - Assert.assertTrue(property7.isPrimitiveType); - Assert.assertTrue(property7.isNotContainer); - Assert.assertTrue(property7.isFloat); - - final CodegenProperty property8 = vars.get(7); - Assert.assertEquals(property8.name, "intProp"); - Assert.assertEquals(property8.baseName, "intProp"); - Assert.assertEquals(property8.datatype, "Integer"); - Assert.assertEquals(property8.baseType, "Integer"); - Assert.assertEquals(property8.example, "123"); - Assert.assertNull(property8.defaultValue); - Assert.assertTrue(property8.hasMore); - Assert.assertTrue(property8.isPrimitiveType); - Assert.assertTrue(property8.isNotContainer); - Assert.assertTrue(property8.isInteger); - - final CodegenProperty property9 = vars.get(8); - Assert.assertEquals(property9.name, "longProp"); - Assert.assertEquals(property9.baseName, "longProp"); - Assert.assertEquals(property9.datatype, "Long"); - Assert.assertEquals(property9.baseType, "Long"); - Assert.assertEquals(property9.example, "123456789L"); - Assert.assertNull(property9.defaultValue); - Assert.assertTrue(property9.hasMore); - Assert.assertTrue(property9.isPrimitiveType); - Assert.assertTrue(property9.isNotContainer); - Assert.assertTrue(property9.isLong); - - final CodegenProperty property10 = vars.get(9); - Assert.assertEquals(property10.name, "stringProp"); - Assert.assertEquals(property10.baseName, "stringProp"); - Assert.assertEquals(property10.datatype, "String"); - Assert.assertEquals(property10.baseType, "String"); - Assert.assertEquals(property10.example, "'aeiou'"); - Assert.assertNull(property10.defaultValue); - Assert.assertTrue(property10.hasMore); - Assert.assertTrue(property10.isPrimitiveType); - Assert.assertTrue(property10.isNotContainer); - Assert.assertTrue(property10.isString); - - final CodegenProperty property11 = vars.get(10); - Assert.assertEquals(property11.name, "baseIntProp"); - Assert.assertEquals(property11.baseName, "baseIntProp"); - Assert.assertEquals(property11.datatype, "Integer"); - Assert.assertEquals(property11.baseType, "Integer"); - Assert.assertEquals(property11.example, "123"); - Assert.assertNull(property11.defaultValue); - Assert.assertTrue(property11.hasMore); - Assert.assertTrue(property11.isPrimitiveType); - Assert.assertTrue(property11.isNotContainer); - Assert.assertTrue(property11.isInteger); - - final CodegenProperty property12 = vars.get(11); - Assert.assertEquals(property12.name, "passwordProp"); - Assert.assertEquals(property12.baseName, "passwordProp"); - Assert.assertEquals(property12.datatype, "String"); - Assert.assertEquals(property12.baseType, "String"); - Assert.assertEquals(property12.example, "'password123'"); - Assert.assertNull(property12.defaultValue); - Assert.assertTrue(property12.hasMore); - Assert.assertTrue(property12.isPrimitiveType); - Assert.assertTrue(property12.isNotContainer); - - final CodegenProperty property13 = vars.get(12); - Assert.assertEquals(property13.name, "uuidProp"); - Assert.assertEquals(property13.baseName, "uuidProp"); - Assert.assertEquals(property13.datatype, "String"); - Assert.assertEquals(property13.baseType, "String"); - Assert.assertEquals(property13.example, "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'"); - Assert.assertNull(property13.defaultValue); - Assert.assertTrue(property13.hasMore); - Assert.assertTrue(property13.isPrimitiveType); - Assert.assertTrue(property13.isNotContainer); - - final CodegenProperty property14 = vars.get(13); - Assert.assertEquals(property14.name, "byteArrProp"); - Assert.assertEquals(property14.baseName, "byteArrProp"); - Assert.assertEquals(property14.datatype, "Blob"); - Assert.assertEquals(property14.baseType, "Blob"); - Assert.assertEquals(property14.example, "EncodingUtil.base64Decode('VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu')"); - Assert.assertNull(property14.defaultValue); - Assert.assertTrue(property14.hasMore); - Assert.assertTrue(property14.isPrimitiveType); - Assert.assertTrue(property14.isNotContainer); - Assert.assertTrue(property14.isByteArray); - - final CodegenProperty property15 = vars.get(14); - Assert.assertEquals(property15.name, "binaryProp"); - Assert.assertEquals(property15.baseName, "binaryProp"); - Assert.assertEquals(property15.datatype, "String"); - Assert.assertEquals(property15.baseType, "String"); - Assert.assertEquals(property15.example, ""); - Assert.assertNull(property15.defaultValue); - Assert.assertFalse(property15.hasMore); - Assert.assertTrue(property15.isPrimitiveType); - Assert.assertTrue(property15.isNotContainer); - Assert.assertTrue(property15.isBinary); - } -// -// @Test(description = "convert a model with list property") -// public void listPropertyTest() { -// final Model model = new ModelImpl() -// .description("a sample model") -// .property("id", new LongProperty()) -// .property("urls", new ArrayProperty() -// .items(new StringProperty())) -// .required("id"); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.description, "a sample model"); -// Assert.assertEquals(cm.vars.size(), 2); -// -// final CodegenProperty property = cm.vars.get(1); -// Assert.assertEquals(property.baseName, "urls"); -// Assert.assertEquals(property.getter, "getUrls"); -// Assert.assertEquals(property.setter, "setUrls"); -// Assert.assertEquals(property.datatype, "List"); -// Assert.assertEquals(property.name, "urls"); -// Assert.assertEquals(property.defaultValue, "new ArrayList()"); -// Assert.assertEquals(property.baseType, "List"); -// Assert.assertEquals(property.containerType, "array"); -// Assert.assertFalse(property.required); -// Assert.assertTrue(property.isContainer); -// } -// -// @Test(description = "convert a model with a map property") -// public void mapPropertyTest() { -// final Model model = new ModelImpl() -// .description("a sample model") -// .property("translations", new MapProperty() -// .additionalProperties(new StringProperty())) -// .required("id"); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.description, "a sample model"); -// Assert.assertEquals(cm.vars.size(), 1); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "translations"); -// Assert.assertEquals(property.getter, "getTranslations"); -// Assert.assertEquals(property.setter, "setTranslations"); -// Assert.assertEquals(property.datatype, "Map"); -// Assert.assertEquals(property.name, "translations"); -// Assert.assertEquals(property.defaultValue, "new HashMap()"); -// Assert.assertEquals(property.baseType, "Map"); -// Assert.assertEquals(property.containerType, "map"); -// Assert.assertFalse(property.required); -// Assert.assertTrue(property.isContainer); -// } -// -// @Test(description = "convert a model with a map with complex list property") -// public void mapWithListPropertyTest() { -// final Model model = new ModelImpl() -// .description("a sample model") -// .property("translations", -// new MapProperty().additionalProperties(new ArrayProperty().items(new RefProperty("Pet")))) -// .required("id"); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.description, "a sample model"); -// Assert.assertEquals(cm.vars.size(), 1); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "translations"); -// Assert.assertEquals(property.getter, "getTranslations"); -// Assert.assertEquals(property.setter, "setTranslations"); -// Assert.assertEquals(property.datatype, "Map>"); -// Assert.assertEquals(property.name, "translations"); -// Assert.assertEquals(property.defaultValue, "new HashMap>()"); -// Assert.assertEquals(property.baseType, "Map"); -// Assert.assertEquals(property.containerType, "map"); -// Assert.assertFalse(property.required); -// Assert.assertTrue(property.isContainer); -// } -// -// @Test(description = "convert a model with a 2D list property") -// public void list2DPropertyTest() { -// final Model model = new ModelImpl().name("sample").property("list2D", new ArrayProperty().items( -// new ArrayProperty().items(new RefProperty("Pet")))); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.vars.size(), 1); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "list2D"); -// Assert.assertEquals(property.getter, "getList2D"); -// Assert.assertEquals(property.setter, "setList2D"); -// Assert.assertEquals(property.datatype, "List>"); -// Assert.assertEquals(property.name, "list2D"); -// Assert.assertEquals(property.defaultValue, "new ArrayList>()"); -// Assert.assertEquals(property.baseType, "List"); -// Assert.assertEquals(property.containerType, "array"); -// Assert.assertFalse(property.required); -// Assert.assertTrue(property.isContainer); -// } -// -// @Test(description = "convert a model with complex properties") -// public void complexPropertiesTest() { -// final Model model = new ModelImpl().description("a sample model") -// .property("children", new RefProperty("#/definitions/Children")); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.description, "a sample model"); -// Assert.assertEquals(cm.vars.size(), 1); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "children"); -// Assert.assertEquals(property.getter, "getChildren"); -// Assert.assertEquals(property.setter, "setChildren"); -// Assert.assertEquals(property.datatype, "Children"); -// Assert.assertEquals(property.name, "children"); -// Assert.assertEquals(property.defaultValue, "null"); -// Assert.assertEquals(property.baseType, "Children"); -// Assert.assertFalse(property.required); -// Assert.assertTrue(property.isNotContainer); -// } -// -// @Test(description = "convert a model with complex list property") -// public void complexListPropertyTest() { -// final Model model = new ModelImpl() -// .description("a sample model") -// .property("children", new ArrayProperty().items(new RefProperty("#/definitions/Children"))); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.description, "a sample model"); -// Assert.assertEquals(cm.vars.size(), 1); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "children"); -// Assert.assertEquals(property.complexType, "Children"); -// Assert.assertEquals(property.getter, "getChildren"); -// Assert.assertEquals(property.setter, "setChildren"); -// Assert.assertEquals(property.datatype, "List"); -// Assert.assertEquals(property.name, "children"); -// Assert.assertEquals(property.defaultValue, "new ArrayList()"); -// Assert.assertEquals(property.baseType, "List"); -// Assert.assertEquals(property.containerType, "array"); -// Assert.assertFalse(property.required); -// Assert.assertTrue(property.isContainer); -// } -// -// @Test(description = "convert a model with complex map property") -// public void complexMapPropertyTest() { -// final Model model = new ModelImpl() -// .description("a sample model") -// .property("children", new MapProperty().additionalProperties(new RefProperty("#/definitions/Children"))); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.description, "a sample model"); -// Assert.assertEquals(cm.vars.size(), 1); -// Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Map", "List", "Children")).size(), 3); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "children"); -// Assert.assertEquals(property.complexType, "Children"); -// Assert.assertEquals(property.getter, "getChildren"); -// Assert.assertEquals(property.setter, "setChildren"); -// Assert.assertEquals(property.datatype, "Map"); -// Assert.assertEquals(property.name, "children"); -// Assert.assertEquals(property.defaultValue, "new HashMap()"); -// Assert.assertEquals(property.baseType, "Map"); -// Assert.assertEquals(property.containerType, "map"); -// Assert.assertFalse(property.required); -// Assert.assertTrue(property.isContainer); -// Assert.assertFalse(property.isNotContainer); -// -// } -// -// @Test(description = "convert an array model") -// public void arrayModelTest() { -// final Model model = new ArrayModel() -// .description("an array model") -// .items(new RefProperty("#/definitions/Children")); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.description, "an array model"); -// Assert.assertEquals(cm.vars.size(), 0); -// Assert.assertEquals(cm.parent, "ArrayList"); -// Assert.assertEquals(cm.imports.size(), 4); -// Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ApiModel", "List", "ArrayList", "Children")).size(), 4); -// } -// -// @Test(description = "convert an map model") -// public void mapModelTest() { -// final Model model = new ModelImpl() -// .description("an map model") -// .additionalProperties(new RefProperty("#/definitions/Children")); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.description, "an map model"); -// Assert.assertEquals(cm.vars.size(), 0); -// Assert.assertEquals(cm.parent, "HashMap"); -// Assert.assertEquals(cm.imports.size(), 4); -// Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ApiModel", "Map", "HashMap", "Children")).size(), 4); -// } -// -// @Test(description = "convert a model with upper-case property names") -// public void upperCaseNamesTest() { -// final Model model = new ModelImpl() -// .description("a model with upper-case property names") -// .property("NAME", new StringProperty()) -// .required("NAME"); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.vars.size(), 1); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "NAME"); -// Assert.assertEquals(property.getter, "getNAME"); -// Assert.assertEquals(property.setter, "setNAME"); -// Assert.assertEquals(property.datatype, "String"); -// Assert.assertEquals(property.name, "NAME"); -// Assert.assertEquals(property.defaultValue, "null"); -// Assert.assertEquals(property.baseType, "String"); -// Assert.assertFalse(property.hasMore); -// Assert.assertTrue(property.required); -// Assert.assertTrue(property.isNotContainer); -// } -// -// @Test(description = "convert a model with a 2nd char upper-case property names") -// public void secondCharUpperCaseNamesTest() { -// final Model model = new ModelImpl() -// .description("a model with a 2nd char upper-case property names") -// .property("pId", new StringProperty()) -// .required("pId"); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.vars.size(), 1); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "pId"); -// Assert.assertEquals(property.getter, "getPId"); -// Assert.assertEquals(property.setter, "setPId"); -// Assert.assertEquals(property.datatype, "String"); -// Assert.assertEquals(property.name, "pId"); -// Assert.assertEquals(property.defaultValue, "null"); -// Assert.assertEquals(property.baseType, "String"); -// Assert.assertFalse(property.hasMore); -// Assert.assertTrue(property.required); -// Assert.assertTrue(property.isNotContainer); -// } -// -// @Test(description = "convert a model starting with two upper-case letter property names") -// public void firstTwoUpperCaseLetterNamesTest() { -// final Model model = new ModelImpl() -// .description("a model with a property name starting with two upper-case letters") -// .property("ATTName", new StringProperty()) -// .required("ATTName"); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.vars.size(), 1); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "ATTName"); -// Assert.assertEquals(property.getter, "getAtTName"); -// Assert.assertEquals(property.setter, "setAtTName"); -// Assert.assertEquals(property.datatype, "String"); -// Assert.assertEquals(property.name, "atTName"); -// Assert.assertEquals(property.defaultValue, "null"); -// Assert.assertEquals(property.baseType, "String"); -// Assert.assertFalse(property.hasMore); -// Assert.assertTrue(property.required); -// Assert.assertTrue(property.isNotContainer); -// } -// -// @Test(description = "convert hyphens per issue 503") -// public void hyphensTest() { -// final Model model = new ModelImpl() -// .description("a sample model") -// .property("created-at", new DateTimeProperty()); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "created-at"); -// Assert.assertEquals(property.getter, "getCreatedAt"); -// Assert.assertEquals(property.setter, "setCreatedAt"); -// Assert.assertEquals(property.name, "createdAt"); -// } -// -// @Test(description = "convert query[password] to queryPassword") -// public void squareBracketsTest() { -// final Model model = new ModelImpl() -// .description("a sample model") -// .property("query[password]", new StringProperty()); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "query[password]"); -// Assert.assertEquals(property.getter, "getQueryPassword"); -// Assert.assertEquals(property.setter, "setQueryPassword"); -// Assert.assertEquals(property.name, "queryPassword"); -// } -// -// @Test(description = "properly escape names per 567") -// public void escapeNamesTest() { -// final Model model = new ModelImpl() -// .description("a sample model") -// .property("created-at", new DateTimeProperty()); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("with.dots", model); -// -// Assert.assertEquals(cm.classname, "WithDots"); -// } -// -// @Test(description = "convert a model with binary data") -// public void binaryDataTest() { -// final Model model = new ModelImpl() -// .description("model with binary") -// .property("inputBinaryData", new ByteArrayProperty()); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "inputBinaryData"); -// Assert.assertEquals(property.getter, "getInputBinaryData"); -// Assert.assertEquals(property.setter, "setInputBinaryData"); -// Assert.assertEquals(property.datatype, "byte[]"); -// Assert.assertEquals(property.name, "inputBinaryData"); -// Assert.assertEquals(property.defaultValue, "null"); -// Assert.assertEquals(property.baseType, "byte[]"); -// Assert.assertFalse(property.hasMore); -// Assert.assertFalse(property.required); -// Assert.assertTrue(property.isNotContainer); -// } -// -// @Test(description = "translate an invalid param name") -// public void invalidParamNameTest() { -// final Model model = new ModelImpl() -// .description("a model with a 2nd char upper-case property names") -// .property("_", new StringProperty()); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// Assert.assertEquals(cm.name, "sample"); -// Assert.assertEquals(cm.classname, "Sample"); -// Assert.assertEquals(cm.vars.size(), 1); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, "_"); -// Assert.assertEquals(property.getter, "getU"); -// Assert.assertEquals(property.setter, "setU"); -// Assert.assertEquals(property.datatype, "String"); -// Assert.assertEquals(property.name, "u"); -// Assert.assertEquals(property.defaultValue, "null"); -// Assert.assertEquals(property.baseType, "String"); -// Assert.assertFalse(property.hasMore); -// Assert.assertTrue(property.isNotContainer); -// } -// -// @Test(description = "convert a parameter") -// public void convertParameterTest() { -// final QueryParameter parameter = new QueryParameter() -// .property(new IntegerProperty()) -// .name("limit") -// .required(true); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenParameter cm = codegen.fromParameter(parameter, null); -// -// Assert.assertNull(cm.allowableValues); -// } -// -// @Test(description = "types used by inner properties should be imported") -// public void mapWithAnListOfBigDecimalTest() { -// final CodegenModel cm1 = new JavaClientCodegen().fromModel("sample", new ModelImpl() -// .description("model with Map>") -// .property("map", new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty())))); -// Assert.assertEquals(cm1.vars.get(0).datatype, "Map>"); -// Assert.assertTrue(cm1.imports.contains("BigDecimal")); -// -// final CodegenModel cm2 = new JavaClientCodegen().fromModel("sample", new ModelImpl() -// .description("model with Map>>") -// .property("map", new MapProperty().additionalProperties(new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty()))))); -// Assert.assertEquals(cm2.vars.get(0).datatype, "Map>>"); -// Assert.assertTrue(cm2.imports.contains("BigDecimal")); -// } -// -// @DataProvider(name = "modelNames") -// public static Object[][] primeNumbers() { -// return new Object[][] { -// {"sample", "Sample"}, -// {"sample_name", "SampleName"}, -// {"sample__name", "SampleName"}, -// {"/sample", "Sample"}, -// {"\\sample", "Sample"}, -// {"sample.name", "SampleName"}, -// {"_sample", "Sample"}, -// {"Sample", "Sample"}, -// }; -// } -// -// @Test(dataProvider = "modelNames", description = "avoid inner class") -// public void modelNameTest(String name, String expectedName) { -// final Model model = new ModelImpl(); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel(name, model); -// -// Assert.assertEquals(cm.name, name); -// Assert.assertEquals(cm.classname, expectedName); -// } -// -// @DataProvider(name = "classProperties") -// public static Object[][] classProperties() { -// return new Object[][] { -// {"class", "getPropertyClass", "setPropertyClass", "propertyClass"}, -// {"_class", "getPropertyClass", "setPropertyClass", "propertyClass"}, -// {"__class", "getPropertyClass", "setPropertyClass", "propertyClass"} -// }; -// } -// -// @Test(dataProvider = "classProperties", description = "handle 'class' properties") -// public void classPropertyTest(String baseName, String getter, String setter, String name) { -// final Model model = new ModelImpl() -// .description("a sample model") -// .property(baseName, new StringProperty()); -// final DefaultCodegen codegen = new JavaClientCodegen(); -// final CodegenModel cm = codegen.fromModel("sample", model); -// -// final CodegenProperty property = cm.vars.get(0); -// Assert.assertEquals(property.baseName, baseName); -// Assert.assertEquals(property.getter, getter); -// Assert.assertEquals(property.setter, setter); -// Assert.assertEquals(property.name, name); -// } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/aspnetcore/AspNetCoreServerOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/aspnetcore/AspNetCoreServerOptionsTest.java deleted file mode 100644 index fb40aebd1afd..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/aspnetcore/AspNetCoreServerOptionsTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.openapitools.codegen.aspnetcore; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.AspNetCoreServerCodegen; -import org.openapitools.codegen.options.AspNetCoreServerOptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class AspNetCoreServerOptionsTest extends AbstractOptionsTest { - - @Tested - private AspNetCoreServerCodegen serverCodegen; - - public AspNetCoreServerOptionsTest() { - super(new AspNetCoreServerOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return serverCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(serverCodegen) {{ - serverCodegen.setPackageName(AspNetCoreServerOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - serverCodegen.setPackageVersion(AspNetCoreServerOptionsProvider.PACKAGE_VERSION_VALUE); - times = 1; - serverCodegen.setSourceFolder(AspNetCoreServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - serverCodegen.setPackageGuid(AspNetCoreServerOptionsProvider.PROJECT_GUID_VALUE); - times = 1; - serverCodegen.useDateTimeOffset(true); - times = 1; - serverCodegen.setUseCollection(false); - times = 1; - serverCodegen.setReturnICollection(false); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java deleted file mode 100644 index b58818b403d8..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java +++ /dev/null @@ -1,370 +0,0 @@ -package org.openapitools.codegen.config; - -import org.openapitools.codegen.ClientOptInput; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.CodegenConfigLoader; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.auth.AuthParser; -import org.openapitools.codegen.languages.JavaClientCodegen; -import io.swagger.models.Swagger; -import io.swagger.models.auth.AuthorizationValue; -import io.swagger.parser.SwaggerParser; -import mockit.Expectations; -import mockit.FullVerifications; -import mockit.Injectable; -import mockit.Mocked; -import mockit.StrictExpectations; -import mockit.Tested; -import org.apache.commons.lang3.SerializationUtils; -import org.testng.annotations.Test; - -import java.nio.file.Paths; -import java.util.List; -import java.util.Map; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -@SuppressWarnings("static-method") -public class CodegenConfiguratorTest { - - @Mocked - SwaggerParser parser; - - @Mocked - AuthParser authParser; - - @Injectable - Swagger swagger; - - @Mocked - CodegenConfigLoader codegenConfigLoader; - - @Injectable - List authorizationValues; - - @Tested - CodegenConfigurator configurator; - - @SuppressWarnings("unused") - @Test - public void testVerbose() throws Exception { - - configurator.setVerbose(true); - - new StrictExpectations(System.class) {{ - System.setProperty("debugSwagger", ""); - times = 1; - System.setProperty("debugModels", ""); - times = 1; - System.setProperty("debugOperations", ""); - times = 1; - System.setProperty("debugSupportingFiles", ""); - times = 1; - }}; - - setupAndRunGenericTest(configurator); - } - - @Test - public void testTemplateDir() throws Exception { - - final String templateDir = "src/test/resources"; - configurator.setTemplateDir(templateDir); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.TEMPLATE_DIR, toAbsolutePathDir(templateDir)); - } - - @SuppressWarnings("unused") - @Test - public void testSystemProperties() throws Exception { - - configurator.addSystemProperty("hello", "world") - .addSystemProperty("foo", "bar"); - - new Expectations(System.class) {{ - System.setProperty("hello", "world"); - times = 1; - System.setProperty("foo", "bar"); - times = 1; - }}; - - setupAndRunGenericTest(configurator); - } - - @Test - public void testSkipOverwrite() throws Exception { - CodegenConfigurator configurator1 = new CodegenConfigurator(); - configurator1.setSkipOverwrite(true); - - ClientOptInput clientOptInput = setupAndRunGenericTest(configurator1); - assertTrue(clientOptInput.getConfig().isSkipOverwrite()); - - CodegenConfigurator configurator2 = new CodegenConfigurator(); - configurator1.setSkipOverwrite(true); - - clientOptInput = setupAndRunGenericTest(configurator2); - assertFalse(clientOptInput.getConfig().isSkipOverwrite()); - } - - @Test - public void testApiPackage() throws Exception { - final String apiPackage = "io.foo.bar.api"; - configurator.setApiPackage(apiPackage); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.API_PACKAGE, apiPackage); - } - - - @Test - public void testModelPackage() throws Exception { - final String modelPackage = "io.foo.bar.models"; - configurator.setModelPackage(modelPackage); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.MODEL_PACKAGE, modelPackage); - } - - @Test - public void testInstantiationTypes() throws Exception { - - configurator.addInstantiationType("foo", "bar") - .addInstantiationType("hello", "world"); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - - assertValueInMap(clientOptInput.getConfig().instantiationTypes(), "foo", "bar"); - assertValueInMap(clientOptInput.getConfig().instantiationTypes(), "hello", "world"); - } - - @Test - public void testTypeMappings() throws Exception { - - configurator.addTypeMapping("foo", "bar") - .addTypeMapping("hello", "world"); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - - assertValueInMap(clientOptInput.getConfig().typeMapping(), "foo", "bar"); - assertValueInMap(clientOptInput.getConfig().typeMapping(), "hello", "world"); - } - - @Test - public void testAdditionalProperties() throws Exception { - - configurator.addAdditionalProperty("foo", "bar") - .addAdditionalProperty("hello", "world") - .addAdditionalProperty("supportJava6", false) - .addAdditionalProperty("useRxJava", true); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - - assertValueInMap(clientOptInput.getConfig().additionalProperties(), "foo", "bar"); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), "hello", "world"); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), "supportJava6", false); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), "useRxJava", true); - } - - @Test - public void testLanguageSpecificPrimitives() throws Exception { - - configurator.addLanguageSpecificPrimitive("foo") - .addLanguageSpecificPrimitive("bar") - .addLanguageSpecificPrimitive("hello") - .addLanguageSpecificPrimitive("world"); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - - assertTrue(clientOptInput.getConfig().languageSpecificPrimitives().contains("foo")); - assertTrue(clientOptInput.getConfig().languageSpecificPrimitives().contains("bar")); - assertTrue(clientOptInput.getConfig().languageSpecificPrimitives().contains("hello")); - assertTrue(clientOptInput.getConfig().languageSpecificPrimitives().contains("world")); - } - - @Test - public void testImportMappings() throws Exception { - - configurator.addImportMapping("foo", "bar") - .addImportMapping("hello", "world"); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - - assertValueInMap(clientOptInput.getConfig().importMapping(), "foo", "bar"); - assertValueInMap(clientOptInput.getConfig().importMapping(), "hello", "world"); - } - - @Test - public void testInvokerPackage() throws Exception { - final String invokerPackage = "io.foo.bar.models"; - configurator.setInvokerPackage(invokerPackage); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.INVOKER_PACKAGE, invokerPackage); - } - - @Test - public void testGroupId() throws Exception { - final String expectedValue = "io.foo.bar.models"; - configurator.setGroupId(expectedValue); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.GROUP_ID, expectedValue); - } - - @Test - public void testArtifactId() throws Exception { - final String expectedValue = "io.foo.bar.models"; - configurator.setArtifactId(expectedValue); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.ARTIFACT_ID, expectedValue); - } - - @Test - public void testArtifactVersion() throws Exception { - final String expectedValue = "1.2.3"; - configurator.setArtifactVersion(expectedValue); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.ARTIFACT_VERSION, expectedValue); - } - - @Test - public void testLibrary() throws Exception { - final String expectedValue = "jersey2"; - - configurator.setLibrary(expectedValue); - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - - assertEquals(clientOptInput.getConfig().getLibrary(), expectedValue); - } - - @Test - public void testDynamicProperties() throws Exception { - configurator.addDynamicProperty(CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); - configurator.addDynamicProperty("supportJava6", false); - configurator.addDynamicProperty("useRxJava", true); - - final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), "supportJava6", false); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), "useRxJava", true); - } - - @Test - public void testFromFile() throws Exception { - final CodegenConfigurator configurator = CodegenConfigurator.fromFile("src/test/resources/sampleConfig.json"); - - assertEquals(configurator.getLang(), "java"); - assertEquals(configurator.getInputSpec(), "swagger.yaml"); - assertEquals(configurator.getOutputDir(), toAbsolutePathDir("src/gen/java")); - assertEquals(configurator.isVerbose(), true); - assertEquals(configurator.isSkipOverwrite(), true); - assertEquals(configurator.getTemplateDir(), toAbsolutePathDir("src/main/resources")); - assertEquals(configurator.getAuth(), "hello:world"); - assertEquals(configurator.getApiPackage(), "io.something.api"); - assertEquals(configurator.getModelPackage(), "io.something.models"); - assertEquals(configurator.getInvokerPackage(), "io.something.invoker"); - assertEquals(configurator.getGroupId(), "io.something"); - assertEquals(configurator.getArtifactId(), "awesome-api"); - assertEquals(configurator.getArtifactVersion(), "1.2.3"); - assertEquals(configurator.getLibrary(), "jersey2"); - - assertEquals(configurator.getSystemProperties().size(), 1); - assertValueInMap(configurator.getSystemProperties(), "systemProp1", "value1"); - - assertEquals(configurator.getInstantiationTypes().size(), 1); - assertValueInMap(configurator.getInstantiationTypes(), "hello", "world"); - - assertEquals(configurator.getTypeMappings().size(), 1); - assertValueInMap(configurator.getTypeMappings(), "foo", "bar"); - - assertEquals(configurator.getAdditionalProperties().size(), 1); - assertValueInMap(configurator.getAdditionalProperties(), "addtProp1", "value2"); - - assertEquals(configurator.getImportMappings().size(), 1); - assertValueInMap(configurator.getImportMappings(), "type1", "import1"); - - - assertEquals(configurator.getLanguageSpecificPrimitives().size(), 1); - assertTrue(configurator.getLanguageSpecificPrimitives().contains("rolex")); - - assertEquals(configurator.getDynamicProperties().size(), 1); - assertValueInMap(configurator.getDynamicProperties(), CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); - - assertEquals(configurator.getIgnoreFileOverride(), "/path/to/override/.swagger-codegen-ignore"); - } - - @Test - public void testCodegenConfiguratorIsSerializable() { - final CodegenConfigurator configurator = CodegenConfigurator.fromFile("src/test/resources/sampleConfig.json"); - // Simply ensure that the object can be serialized - SerializationUtils.serialize(configurator); - } - - @SuppressWarnings("unused") - private ClientOptInput setupAndRunGenericTest(CodegenConfigurator configurator) { - - final String spec = "swagger.yaml"; - final String lang = "java"; - final String outputDir = "src/test/java"; - final String expectedAuth = "hello:world"; - - - configurator.setLang(lang) - .setOutputDir(outputDir) - .setInputSpec(spec) - .setAuth(expectedAuth); - - final CodegenConfig config = new JavaClientCodegen(); - - setupStandardExpectations(spec, lang, configurator.getAuth(), config); - - ClientOptInput result = configurator.toClientOptInput(); - - new FullVerifications() {{ - }}; - - final String expectedOutputDir = toAbsolutePathDir(outputDir); - - assertEquals(result.getConfig().getOutputDir(), expectedOutputDir); - - return result; - } - - private static String toAbsolutePathDir(String outputDir) { - return Paths.get(outputDir).toAbsolutePath().toAbsolutePath().toString(); - } - - @SuppressWarnings("unused") - private void setupStandardExpectations(final String spec, final String languageName, final String auth, final CodegenConfig config) { - - new StrictExpectations() {{ - CodegenConfigLoader.forName(languageName); - times = 1; - result = config; - - AuthParser.parse(auth); times=1; result = authorizationValues; - - new SwaggerParser(); - times = 1; - result = parser; - - parser.read(spec, authorizationValues, true); - times = 1; - result = swagger; - - }}; - } - - private static void assertValueInMap(Map map, String propertyKey, Object expectedPropertyValue) { - assertTrue(map.containsKey(propertyKey)); - assertEquals(map.get(propertyKey), expectedPropertyValue); - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java deleted file mode 100644 index f731c9bd6f7b..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.openapitools.codegen.csharp; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.CSharpClientCodegen; -import org.openapitools.codegen.options.CSharpClientOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class CSharpClientOptionsTest extends AbstractOptionsTest { - - @Tested - private CSharpClientCodegen clientCodegen; - - public CSharpClientOptionsTest() { - super(new CSharpClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setPackageName(CSharpClientOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - clientCodegen.setOptionalMethodArgumentFlag(true); - times = 1; - clientCodegen.setPackageVersion(CSharpClientOptionsProvider.PACKAGE_VERSION_VALUE); - times = 1; - clientCodegen.setOptionalAssemblyInfoFlag(true); - times = 1; - clientCodegen.setSourceFolder(CSharpClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.useDateTimeOffset(true); - times = 1; - clientCodegen.setOptionalProjectFileFlag(true); - times = 1; - clientCodegen.setPackageGuid(CSharpClientOptionsProvider.PACKAGE_GUID_VALUE); - times = 1; - clientCodegen.setUseCollection(false); - times = 1; - clientCodegen.setReturnICollection(false); - times = 1; - clientCodegen.setOptionalEmitDefaultValue(true); - times = 1; - clientCodegen.setGeneratePropertyChanged(true); - times = 1; - clientCodegen.setNonPublicApi(true); - times = 1; - clientCodegen.setInterfacePrefix("X"); - times = 1; - clientCodegen.setAllowUnicodeIdentifiers(Boolean.valueOf(CSharpClientOptionsProvider.ALLOW_UNICODE_IDENTIFIERS_VALUE)); - times = 1; - clientCodegen.setNetCoreProjectFileFlag(false); - times = 1; - clientCodegen.setModelPropertyNaming(CSharpClientOptionsProvider.MODEL_PROPERTY_NAMING); - times = 1; - clientCodegen.setValidatable(true); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java deleted file mode 100644 index a4bff2243310..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java +++ /dev/null @@ -1,378 +0,0 @@ -package org.openapitools.codegen.csharp; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.CSharpClientCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Path; -import io.swagger.models.Swagger; -import io.swagger.models.properties.*; -import io.swagger.parser.SwaggerParser; - -import com.google.common.collect.Sets; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -@SuppressWarnings("static-method") -public class CSharpModelTest { - - @Test(description = "convert a model with array property to default List") - public void arrayPropertyTest() { - final Model model = getArrayTestModel(); - - final DefaultCodegen codegen = new CSharpClientCodegen(); - final CodegenModel generated = codegen.fromModel("sample", model); - - Assert.assertEquals(generated.name, "sample"); - Assert.assertEquals(generated.classname, "Sample"); - Assert.assertEquals(generated.description, "a sample model"); - Assert.assertEquals(generated.vars.size(), 2); - - final CodegenProperty property = generated.vars.get(1); - Assert.assertEquals(property.baseName, "examples"); - Assert.assertEquals(property.getter, "getExamples"); - Assert.assertEquals(property.setter, "setExamples"); - Assert.assertEquals(property.datatype, "List"); - Assert.assertEquals(property.name, "Examples"); - Assert.assertEquals(property.defaultValue, null); - Assert.assertEquals(property.baseType, "List"); - Assert.assertEquals(property.containerType, "array"); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isContainer); - } - - @Test(description = "convert a model with array property to Collection") - public void arrayPropertyCollectionOptionTest() { - final Model model = getArrayTestModel(); - - final CSharpClientCodegen codegen = new CSharpClientCodegen(); - codegen.setUseCollection(true); - - final CodegenModel generated = codegen.fromModel("sample", model); - - Assert.assertEquals(generated.name, "sample"); - Assert.assertEquals(generated.vars.size(), 2); - - final CodegenProperty property = generated.vars.get(1); - Assert.assertEquals(property.baseName, "examples"); - Assert.assertEquals(property.name, "Examples"); - Assert.assertEquals(property.defaultValue, null); - Assert.assertEquals(property.datatype, "Collection"); - Assert.assertEquals(property.baseType, "Collection"); - Assert.assertEquals(property.containerType, "array"); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isContainer); - } - - @Test(description = "convert a model with array property to Collection") - public void arrayPropertyICollectionOptionTest() { - final Model model = getArrayTestModel(); - - final CSharpClientCodegen codegen = new CSharpClientCodegen(); - codegen.setUseCollection(true); - codegen.setReturnICollection(true); - - final CodegenModel generated = codegen.fromModel("sample", model); - - Assert.assertEquals(generated.name, "sample"); - Assert.assertEquals(generated.vars.size(), 2); - - final CodegenProperty property = generated.vars.get(1); - Assert.assertEquals(property.baseName, "examples"); - Assert.assertEquals(property.name, "Examples"); - Assert.assertEquals(property.datatype, "Collection", - "returnICollection option should not modify property datatype"); - Assert.assertEquals(property.defaultValue, null); - Assert.assertEquals(property.baseType, "Collection", - "returnICollection option should not modify property baseType"); - Assert.assertEquals(property.containerType, "array"); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isContainer); - } - - private Model getArrayTestModel() { - return new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("examples", new ArrayProperty().items(new StringProperty())) - .required("id"); - } - - @Test(description = "convert a simple model") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); - final DefaultCodegen codegen = new CSharpClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 3); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "long?"); - Assert.assertEquals(property1.name, "Id"); - Assert.assertNull(property1.defaultValue); - Assert.assertEquals(property1.baseType, "long?"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isPrimitiveType); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.datatype, "string"); - Assert.assertEquals(property2.name, "Name"); - Assert.assertNull(property2.defaultValue); - Assert.assertEquals(property2.baseType, "string"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isPrimitiveType); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.datatype, "DateTime?"); - Assert.assertEquals(property3.name, "CreatedAt"); - Assert.assertNull(property3.defaultValue); - Assert.assertEquals(property3.baseType, "DateTime?"); - Assert.assertFalse(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - } - - @Test(description = "convert a model with list property") - public void listPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id"); - final DefaultCodegen codegen = new CSharpClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 2); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "long?"); - Assert.assertEquals(property1.name, "Id"); - Assert.assertNull(property1.defaultValue); - Assert.assertEquals(property1.baseType, "long?"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isPrimitiveType); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "urls"); - Assert.assertEquals(property2.datatype, "List"); - Assert.assertEquals(property2.name, "Urls"); - Assert.assertNull(property2.defaultValue); - Assert.assertEquals(property2.baseType, "List"); - Assert.assertFalse(property2.hasMore); - Assert.assertEquals(property2.containerType, "array"); - Assert.assertFalse(property2.required); - Assert.assertTrue(property2.isPrimitiveType); - Assert.assertTrue(property2.isContainer); - } - - @Test(description = "convert a model with a map property") - public void mapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); - final DefaultCodegen codegen = new CSharpClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "translations"); - Assert.assertEquals(property1.datatype, "Dictionary"); - Assert.assertEquals(property1.name, "Translations"); - Assert.assertEquals(property1.baseType, "Dictionary"); - Assert.assertEquals(property1.containerType, "map"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - Assert.assertTrue(property1.isPrimitiveType); - } - - @Test(description = "convert a model with complex property") - public void complexPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new CSharpClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.datatype, "Children"); - Assert.assertEquals(property1.name, "Children"); - Assert.assertEquals(property1.baseType, "Children"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isNotContainer); - } - - @Test(description = "convert a model with complex list property") - public void complexListPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); - final DefaultCodegen codegen = new CSharpClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.datatype, "List"); - Assert.assertEquals(property1.name, "Children"); - Assert.assertEquals(property1.baseType, "List"); - Assert.assertEquals(property1.containerType, "array"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - } - - @Test(description = "convert a model with complex map property") - public void complexMapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); - final DefaultCodegen codegen = new CSharpClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.datatype, "Dictionary"); - Assert.assertEquals(property1.name, "Children"); - Assert.assertEquals(property1.baseType, "Dictionary"); - Assert.assertEquals(property1.containerType, "map"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - Assert.assertFalse(property1.isNotContainer); - } - - @Test(description = "convert an array model") - public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new CSharpClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "an array model"); - Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.parent, "List"); - Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - } - - @Test(description = "convert an map model") - public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new CSharpClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a map model"); - Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.parent, "Dictionary"); - Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - } - - @Test(description = "convert an array of array models") - public void arraysOfArraysModelTest() { - final Model model = new ArrayModel() - .description("a sample geolocation model") - .items( - new ArrayProperty().items(new DoubleProperty()) - ); - - final DefaultCodegen codegen = new CSharpClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.parent, "List>"); - } - - @Test(description = "convert an array of array properties") - public void arraysOfArraysPropertyTest() { - final Model model = new ModelImpl() - .description("a sample geolocation model") - .property("points", new ArrayProperty() - .items( - new ArrayProperty().items(new DoubleProperty()) - ) - ); - - final DefaultCodegen codegen = new CSharpClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertNull(cm.parent); - - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "points"); - Assert.assertNull(property1.complexType); - Assert.assertEquals(property1.datatype, "List>"); - Assert.assertEquals(property1.name, "Points"); - Assert.assertEquals(property1.baseType, "List"); - Assert.assertEquals(property1.containerType, "array"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - Assert.assertFalse(property1.isNotContainer); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CsharpClientGeneralEnumSupportIntegrationTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CsharpClientGeneralEnumSupportIntegrationTest.java deleted file mode 100644 index 99151878ca79..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CsharpClientGeneralEnumSupportIntegrationTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.openapitools.codegen.csharp; - -import com.google.common.collect.ImmutableMap; -import org.openapitools.codegen.AbstractIntegrationTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.CSharpClientCodegen; -import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -public class CsharpClientGeneralEnumSupportIntegrationTest extends AbstractIntegrationTest { - public CsharpClientGeneralEnumSupportIntegrationTest() { - generateSwaggerMetadata = false; - - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - systemPropertyOverrides = builder - .put(CodegenConstants.APIS, Boolean.FALSE.toString()) - .put(CodegenConstants.MODELS, Boolean.TRUE.toString()) - .put(CodegenConstants.API_DOCS, Boolean.FALSE.toString()) - .put(CodegenConstants.MODEL_DOCS, Boolean.FALSE.toString()) - .put(CodegenConstants.API_TESTS, Boolean.FALSE.toString()) - .put(CodegenConstants.MODEL_TESTS, Boolean.FALSE.toString()) - .put(CodegenConstants.SUPPORTING_FILES, Boolean.FALSE.toString()) - .build(); - } - - @Override - protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { - return new IntegrationTestPathsConfig("csharp/general/enum-support"); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return new CSharpClientCodegen(); - } - - @Override - protected Map configProperties() { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.EXCLUDE_TESTS, Boolean.TRUE.toString()); - return properties; - } - - // TODO: Remove this when super.generatesCorrectDirectoryStructure() is re-enabled. - @Test(description = "Verify csharp enum support, generalized across supported C# versions.") - public void test() throws IOException { - this.generatesCorrectDirectoryStructure(); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CsharpModelEnumTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CsharpModelEnumTest.java deleted file mode 100644 index 9b373ea55ef4..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/csharp/CsharpModelEnumTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.openapitools.codegen.csharp; - - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.CSharpClientCodegen; -import io.swagger.models.ComposedModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.RefModel; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public class CsharpModelEnumTest { - @Test(description = "not override identical parent enums") - public void overrideEnumTest() { - final StringProperty identicalEnumProperty = new StringProperty(); - identicalEnumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); - - final StringProperty subEnumProperty = new StringProperty(); - subEnumProperty.setEnum(Arrays.asList("SUB1", "SUB2", "SUB3")); - - // Add one enum property to the parent - final Map parentProperties = new HashMap(); - parentProperties.put("sharedThing", identicalEnumProperty); - - // Add TWO enums to the subType model; one of which is identical to the one in parent class - final Map subProperties = new HashMap(); - subProperties.put("sharedThing", identicalEnumProperty); - subProperties.put("unsharedThing", identicalEnumProperty); - - final ModelImpl parentModel = new ModelImpl() - .description("parentModel"); - parentModel.setProperties(parentProperties); - parentModel.name("parentModel"); - - final ModelImpl subModel = new ModelImpl() - .description("subModel"); - subModel.setProperties(subProperties); - subModel.name("subModel"); - - final ComposedModel model = new ComposedModel() - .parent(new RefModel(parentModel.getName())) - .child(subModel) - .interfaces(new ArrayList()); - - final DefaultCodegen codegen = new CSharpClientCodegen(); - final Map allModels = new HashMap<>(); - allModels.put("ParentModel", parentModel); - allModels.put("SubModel", subModel); - - final CodegenModel cm = codegen.fromModel("sample", model, allModels); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.parent, "ParentModel"); - Assert.assertTrue(cm.imports.contains("ParentModel")); - - // Assert that only the unshared/uninherited enum remains - Assert.assertEquals(cm.vars.size(), 1); - final CodegenProperty enumVar = cm.vars.get(0); - Assert.assertEquals(enumVar.baseName, "unsharedThing"); - Assert.assertEquals(enumVar.datatype, "string"); - Assert.assertEquals(enumVar.datatypeWithEnum, "UnsharedThingEnum"); - Assert.assertTrue(enumVar.isEnum); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java deleted file mode 100644 index ff12c3c4a7ad..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openapitools.codegen.csharpdotnettwo; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.CsharpDotNet2ClientCodegen; -import org.openapitools.codegen.options.CsharpDotNet2ClientOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class CsharpDotNet2ClientOptionsTest extends AbstractOptionsTest { - - @Tested - private CsharpDotNet2ClientCodegen clientCodegen; - - public CsharpDotNet2ClientOptionsTest() { - super(new CsharpDotNet2ClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setPackageName(CsharpDotNet2ClientOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - clientCodegen.setPackageVersion(CsharpDotNet2ClientOptionsProvider.PACKAGE_VERSION_VALUE); - times = 1; - clientCodegen.setClientPackage(CsharpDotNet2ClientOptionsProvider.CLIENT_PACKAGE_VALUE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/eiffel/EiffelClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/eiffel/EiffelClientOptionsTest.java deleted file mode 100644 index 57973b2f2ae4..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/eiffel/EiffelClientOptionsTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.openapitools.codegen.eiffel; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.EiffelClientCodegen; -import org.openapitools.codegen.options.EiffelClientOptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class EiffelClientOptionsTest extends AbstractOptionsTest { - - @Tested - private EiffelClientCodegen clientCodegen; - - public EiffelClientOptionsTest() { - super(new EiffelClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setPackageName(EiffelClientOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/eiffel/EiffelModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/eiffel/EiffelModelTest.java deleted file mode 100644 index 9a5974c3af2e..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/eiffel/EiffelModelTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.openapitools.codegen.eiffel; -import org.testng.Assert; -import org.testng.annotations.Test; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.EiffelClientCodegen; -import org.openapitools.codegen.languages.KotlinClientCodegen; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.StringProperty; - -@SuppressWarnings("static-method") -public class EiffelModelTest { - - @Test(description = "convert a simple Eiffel model") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); - final DefaultCodegen codegen = new EiffelClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "SAMPLE"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 3); - Assert.assertEquals(cm.imports.size(), 2); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "INTEGER_64"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); - Assert.assertEquals(property1.baseType, "INTEGER_64"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isPrimitiveType); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.datatype, "STRING_32"); - Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property1.defaultValue, "null"); - Assert.assertEquals(property2.baseType, "STRING_32"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertFalse(property2.isPrimitiveType); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.complexType, "DATE_TIME"); - Assert.assertEquals(property3.datatype, "DATE_TIME"); - Assert.assertEquals(property3.name, "created_at"); - Assert.assertEquals(property1.defaultValue, "null"); - Assert.assertEquals(property3.baseType, "DATE_TIME"); - Assert.assertFalse(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - } - - @Test(description = "convert a model with list property") - public void listPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id"); - final DefaultCodegen codegen = new EiffelClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "SAMPLE"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 2); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "INTEGER_64"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); - Assert.assertEquals(property1.baseType, "INTEGER_64"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isPrimitiveType); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "urls"); - Assert.assertEquals(property2.datatype, "LIST [STRING_32]"); - Assert.assertEquals(property2.name, "urls"); - Assert.assertEquals(property2.baseType, "LIST"); - Assert.assertFalse(property2.hasMore); - Assert.assertEquals(property2.containerType, "array"); - Assert.assertFalse(property2.required); - Assert.assertFalse(property2.isPrimitiveType); - Assert.assertTrue(property2.isContainer); - } - - - - @Test(description = "convert a model with a map property") - public void mapPropertyTest() { - final Model model = getMapModel(); - final DefaultCodegen codegen = new EiffelClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "SAMPLE"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "mapping"); - Assert.assertEquals(property1.datatype, "STRING_TABLE[STRING_32]"); - Assert.assertEquals(property1.name, "mapping"); - Assert.assertEquals(property1.baseType, "STRING_TABLE"); - Assert.assertEquals(property1.containerType, "map"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - Assert.assertFalse(property1.isPrimitiveType); - } - - private Model getMapModel() { - return new ModelImpl() - .description("a sample model") - .property("mapping", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java deleted file mode 100644 index b83271738343..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.openapitools.codegen.flash; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.FlashClientCodegen; -import org.openapitools.codegen.options.FlashClienOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class FlashClienOptionsTest extends AbstractOptionsTest { - - @Tested - private FlashClientCodegen clientCodegen; - - public FlashClienOptionsTest() { - super(new FlashClienOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setPackageName(FlashClienOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - clientCodegen.setPackageVersion(FlashClienOptionsProvider.PACKAGE_VERSION_VALUE); - times = 1; - clientCodegen.setInvokerPackage(FlashClienOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setSourceFolder(FlashClienOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/haskellhttpclient/HaskellHttpClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/haskellhttpclient/HaskellHttpClientOptionsTest.java deleted file mode 100644 index 844badbe0af4..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/haskellhttpclient/HaskellHttpClientOptionsTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.openapitools.codegen.haskellhttpclient; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.HaskellHttpClientCodegen; -import org.openapitools.codegen.options.HaskellHttpClientOptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class HaskellHttpClientOptionsTest extends AbstractOptionsTest { - - @Tested - private HaskellHttpClientCodegen clientCodegen; - - public HaskellHttpClientOptionsTest() { - super(new HaskellHttpClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(HaskellHttpClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setAllowNonUniqueOperationIds(Boolean.valueOf(HaskellHttpClientOptionsProvider.ALLOW_NONUNIQUE_OPERATION_IDS)); - times = 1; - clientCodegen.setAllowFromJsonNulls(Boolean.valueOf(HaskellHttpClientOptionsProvider.ALLOW_FROMJSON_NULLS)); - times = 1; - clientCodegen.setAllowToJsonNulls(Boolean.valueOf(HaskellHttpClientOptionsProvider.ALLOW_TOJSON_NULLS)); - times = 1; - clientCodegen.setGenerateModelConstructors(Boolean.valueOf(HaskellHttpClientOptionsProvider.GENERATE_MODEL_CONSTRUCTORS)); - times = 1; - clientCodegen.setGenerateEnums(Boolean.valueOf(HaskellHttpClientOptionsProvider.GENERATE_ENUMS)); - times = 1; - clientCodegen.setGenerateFormUrlEncodedInstances(Boolean.valueOf(HaskellHttpClientOptionsProvider.GENERATE_FORM_URLENCODED_INSTANCES)); - times = 1; - clientCodegen.setGenerateLenses(Boolean.valueOf(HaskellHttpClientOptionsProvider.GENERATE_LENSES)); - times = 1; - clientCodegen.setInlineMimeTypes(Boolean.valueOf(HaskellHttpClientOptionsProvider.INLINE_MIME_TYPES)); - times = 1; - clientCodegen.setModelDeriving(HaskellHttpClientOptionsProvider.MODEL_DERIVING); - times = 1; - clientCodegen.setDateTimeFormat(HaskellHttpClientOptionsProvider.DATETIME_FORMAT); - times = 1; - clientCodegen.setDateFormat(HaskellHttpClientOptionsProvider.DATE_FORMAT); - times = 1; - clientCodegen.setStrictFields(Boolean.valueOf(HaskellHttpClientOptionsProvider.STRICT_FIELDS)); - times = 1; - clientCodegen.setUseMonadLogger(Boolean.valueOf(HaskellHttpClientOptionsProvider.USE_MONAD_LOGGER)); - times = 1; - clientCodegen.setCabalPackage(HaskellHttpClientOptionsProvider.CABAL_PACKAGE); - times = 1; - clientCodegen.setCabalVersion(HaskellHttpClientOptionsProvider.CABAL_VERSION); - times = 1; - clientCodegen.setBaseModule(HaskellHttpClientOptionsProvider.BASE_MODULE); - times = 1; - clientCodegen.setRequestType(HaskellHttpClientOptionsProvider.REQUEST_TYPE); - times = 1; - clientCodegen.setConfigType(HaskellHttpClientOptionsProvider.CONFIG_TYPE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/haskellhttpclient/HaskellHttpClientTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/haskellhttpclient/HaskellHttpClientTest.java deleted file mode 100644 index 51113844f3cb..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/haskellhttpclient/HaskellHttpClientTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.openapitools.codegen.haskellhttpclient; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class HaskellHttpClientTest { - - @Test(description = "convert a haskell model with dots") - public void modelTest() { - Assert.assertEquals(true, true); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java deleted file mode 100644 index 12672229f9b0..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java +++ /dev/null @@ -1,154 +0,0 @@ -package org.openapitools.codegen.ignore; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.SystemUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.*; -import static org.testng.Assert.*; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; - -public class CodegenIgnoreProcessorTest { - - private static final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessorTest.class); - - private Boolean allowed; - private Boolean skip = false; - private final String filename; - private final String ignoreDefinition; - private final String description; - private String outputDir; - private File target; - private Path temp; - - private CodegenIgnoreProcessorTest(String filename, String ignoreDefinition, String description) throws IOException { - this.filename = filename; - this.ignoreDefinition = ignoreDefinition; - this.description = description; - } - - CodegenIgnoreProcessorTest allowed() { - this.allowed = true; - return this; - } - - CodegenIgnoreProcessorTest skipOnCondition(Boolean condition) { - this.skip = Boolean.TRUE.equals(condition); - return this; - } - - CodegenIgnoreProcessorTest ignored() { - this.allowed = false; - return this; - } - - private void prepareTestFiles() throws IOException { - // NOTE: Each test needs its own directory because .swagger-codegen-ignore needs to exist at the root. - temp = Files.createTempDirectory(getClass().getSimpleName()); - this.outputDir = temp.toFile().getAbsolutePath(); - - target = new File(this.outputDir, this.filename); - - boolean mkdirs = target.getParentFile().mkdirs(); - if(!mkdirs) { - LOGGER.warn("Failed to create directories for CodegenIgnoreProcessorTest test file. Directory may already exist."); - } - - Path created = Files.createFile(target.toPath()); - if(!created.toFile().exists()) { - throw new IOException("Failed to write CodegenIgnoreProcessorTest test file."); - } - - // System.out.print(String.format("Created codegen ignore processor test file: %s\n", created.toAbsolutePath())); - File ignoreFile = new File(this.outputDir, ".swagger-codegen-ignore"); - try (FileOutputStream stream = new FileOutputStream(ignoreFile)) { - stream.write(this.ignoreDefinition.getBytes()); - } - } - - @AfterTest - public void afterTest() throws IOException { - if(temp != null && temp.toFile().exists() && temp.toFile().isDirectory()) { - FileUtils.deleteDirectory(temp.toFile()); - } - } - - @Test - public void evaluate() { - if(this.skip) { - return; - } - - // Arrange - try { - // Lazily setup files to avoid conflicts and creation when these tests may not even run. - prepareTestFiles(); - } catch (IOException e) { - e.printStackTrace(); - fail("Failed to prepare test files. " + e.getMessage()); - } - CodegenIgnoreProcessor processor = new CodegenIgnoreProcessor(outputDir); - Boolean actual = null; - - // Act - actual = processor.allowsFile(target); - - // Assert - assertEquals(actual, this.allowed, this.description); - } - - @Factory - public static Object[] factoryMethod() throws IOException { - return new Object[] { - // Matching filenames - new CodegenIgnoreProcessorTest("build.sh", "build.sh", "A file when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("build.sh", "*.sh", "A file when matching glob should ignore.").ignored(), - new CodegenIgnoreProcessorTest("src/build.sh", "*.sh", "A nested file when matching non-nested simple glob should allow.").allowed(), - new CodegenIgnoreProcessorTest("src/build.sh", "**/build.sh", "A file when matching nested files should ignore.").ignored(), - new CodegenIgnoreProcessorTest("Build.sh", "build.sh", "A file when non-matching should allow.").allowed().skipOnCondition(SystemUtils.IS_OS_WINDOWS), - new CodegenIgnoreProcessorTest("build.sh", "/build.sh", "A rooted file when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("nested/build.sh", "/build.sh", "A rooted file definition when non-matching should allow.").allowed(), - new CodegenIgnoreProcessorTest("src/IO.Swagger.Test/Model/AnimalFarmTests.cs", "src/IO.Swagger.Test/Model/AnimalFarmTests.cs", "A file when matching exactly should ignore.").ignored(), - - // Matching spaces in filenames - new CodegenIgnoreProcessorTest("src/properly escaped.txt", "**/properly escaped.txt", "A file when matching nested files with spaces in the name should ignore.").ignored(), - new CodegenIgnoreProcessorTest("src/improperly escaped.txt", "**/improperly\\ escaped.txt", "A file when matching nested files with spaces in the name (improperly escaped rule) should allow.").allowed(), - - // Match All - new CodegenIgnoreProcessorTest("docs/somefile.md", "docs/**", "A recursive file (0 level) when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/somefile.md", "docs/**", "A recursive file (1 level) when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/somefile.md", "docs/**", "A recursive file (n level) when matching should ignore.").ignored(), - - // Match Any - new CodegenIgnoreProcessorTest("docs/1/2/3/somefile.md", "docs/**/somefile.*", "A recursive file with match-any extension when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/somefile.java", "docs/**/*.java", "A recursive file with match-any file name when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/4/somefile.md", "docs/**/*", "A recursive file with match-any file name when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/4/5/somefile.md", "docs/**/anyfile.*", "A recursive file with match-any extension when non-matching should allow.").allowed(), - - // Directory matches - new CodegenIgnoreProcessorTest("docs/1/Users/a", "docs/**/Users/", "A directory rule when matching should be ignored.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/Users1/a", "docs/**/Users/", "A directory rule when non-matching should be allowed.").allowed(), - - // Negation of excluded recursive files - new CodegenIgnoreProcessorTest("docs/UserApi.md", "docs/**\n!docs/UserApi.md", "A pattern negating a previous ignore FILE rule should be allowed.").allowed(), - - // Negation of excluded directories - new CodegenIgnoreProcessorTest("docs/1/Users/UserApi.md", "docs/**/Users/\n!docs/1/Users/UserApi.md", "A pattern negating a previous ignore DIRECTORY rule should be ignored.").ignored(), - - // Other matches which may not be parsed for correctness, but are free because of PathMatcher - new CodegenIgnoreProcessorTest("docs/1/2/3/Some99File.md", "**/*[0-9]*", "A file when matching against simple regex patterns when matching should be ignored.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/SomeFile.md", "**/*.{java,md}", "A file when matching against grouped subpatterns for extension when matching (md) should be ignored.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/SomeFile.java", "**/*.{java,md}", "A file when matching against grouped subpatterns for extension when matching (java) should be ignored.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/SomeFile.txt", "**/*.{java,md}", "A file when matching against grouped subpatterns for extension when non-matching should be allowed.").allowed(), - - new CodegenIgnoreProcessorTest("docs/1/2/3/foo.c", "**/*.?", "A file when matching against required single-character extension when matching should be ignored.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/foo.cc", "**/*.?", "A file when matching against required single-character extension when non-matching should be allowed.").allowed() - - }; - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java deleted file mode 100644 index 1e79ed932621..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.openapitools.codegen.ignore.rules; - -import org.testng.annotations.Test; - -import java.util.Arrays; -import java.util.List; - -import static org.testng.Assert.*; - -public class FileRuleTest { - @Test - public void testMatchComplex() throws Exception { - // Arrange - final String definition = "path/to/**/complex/*.txt"; - final String relativePath = "path/to/some/nested/complex/xyzzy.txt"; - - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "path"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "to"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.MATCH_ALL), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "complex"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".txt") - ); - - Rule rule = new FileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertTrue(actual); - } - - @Test - public void testNonMatchComplex() throws Exception { - // Arrange - final String definition = "path/to/**/complex/*.txt"; - final String relativePath = "path/to/some/nested/invalid/xyzzy.txt"; - - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "path"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "to"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.MATCH_ALL), - new Part(IgnoreLineParser.Token.TEXT, "complex"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".txt") - ); - - Rule rule = new FileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertFalse(actual); - } - - @Test - public void testGlobbingRecursive() throws Exception { - // Arrange - final String definition = "*.txt"; - final String relativePath = "path/to/some/nested/location/xyzzy.txt"; - - // Act - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.MATCH_ALL), - new Part(IgnoreLineParser.Token.DIRECTORY_MARKER), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".txt") - ); - - Rule rule = new FileRule(syntax, definition); - Boolean actual = rule.matches(relativePath); - - // Assert - assertTrue(actual); - } - - @Test - public void testGlobbingNotRecursive() throws Exception { - // Arrange - final String definition = "*.txt"; - final String relativePath = "path/to/some/nested/location/xyzzy.txt"; - - // Act - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".txt") - ); - - Rule rule = new FileRule(syntax, definition); - Boolean actual = rule.matches(relativePath); - - // Assert - assertFalse(actual); - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/rules/IgnoreLineParserTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/rules/IgnoreLineParserTest.java deleted file mode 100644 index 67ee1b02ae17..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/rules/IgnoreLineParserTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package org.openapitools.codegen.ignore.rules; - -import org.testng.annotations.Test; - -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; - -import static org.testng.Assert.*; - -public class IgnoreLineParserTest { - private IgnoreLineParser.Token verifyInputToSingleToken(final String input, IgnoreLineParser.Token token) throws ParserException { - // Act - List result = IgnoreLineParser.parse(input); - - // Assert - assertNotNull(result); - assertEquals(result.size(), 1); - IgnoreLineParser.Token actual = result.get(0).getToken(); - assertEquals(actual, token); - - return actual; - } - - @Test - public void parseMatchAll() throws Exception { - verifyInputToSingleToken("**", IgnoreLineParser.Token.MATCH_ALL); - } - - @Test - public void parseMatchAny() throws Exception { - verifyInputToSingleToken("*", IgnoreLineParser.Token.MATCH_ANY); - } - - @Test(expectedExceptions = ParserException.class, - expectedExceptionsMessageRegExp = "Negation with no negated pattern\\.") - public void parseNegate() throws Exception { - verifyInputToSingleToken("!", IgnoreLineParser.Token.NEGATE); - - // Assert - fail("Expected simple pattern '!' to throw a ParserException."); - } - - @Test - public void parseComment() throws Exception { - // Arrange - final String input = "# This is a comment"; - Part actual = null; - - // Act - List result = IgnoreLineParser.parse(input); - - // Assert - assertEquals(result.size(), 1); - actual = result.get(0); - assertEquals(actual.getToken(), IgnoreLineParser.Token.COMMENT); - assertEquals(actual.getValue(), input); - } - - @Test - public void parseEscapedExclamation() throws Exception { - final String input = "\\!"; - verifyInputToSingleToken(input, IgnoreLineParser.Token.ESCAPED_EXCLAMATION); - } - - @Test - public void parseEscapedSpace() throws Exception { - final String input = "\\ "; - verifyInputToSingleToken(input, IgnoreLineParser.Token.ESCAPED_SPACE); - } - - @Test - public void parseDirectoryMarker() throws Exception { - // Arrange - final String input = "foo/"; - Part actual = null; - - // Act - List result = IgnoreLineParser.parse(input); - - // Assert - assertEquals(result.size(), 2); - actual = result.get(0); - assertEquals(actual.getToken(), IgnoreLineParser.Token.TEXT); - assertEquals(actual.getValue(), "foo"); - actual = result.get(1); - assertEquals(actual.getToken(), IgnoreLineParser.Token.DIRECTORY_MARKER); - } - - @Test - public void parseRooted() throws Exception { - // Arrange - final String input = "/abcd"; - Part actual = null; - - // Act - List result = IgnoreLineParser.parse(input); - - // Assert - assertEquals(result.size(), 2); - actual = result.get(0); - assertEquals(actual.getToken(), IgnoreLineParser.Token.ROOTED_MARKER); - actual = result.get(1); - assertEquals(actual.getToken(), IgnoreLineParser.Token.TEXT); - assertEquals(actual.getValue(), "abcd"); - } - - @Test - public void parseComplex() throws Exception { - // Arrange - final String input = "**/abcd/**/foo/bar/sample.txt"; - Part current = null; - - // Act - Queue result = new LinkedList<>(IgnoreLineParser.parse(input)); - - // Assert - current = result.remove(); - assertEquals(current.getToken(), IgnoreLineParser.Token.MATCH_ALL); - current = result.remove(); - assertEquals(current.getToken(), IgnoreLineParser.Token.PATH_DELIM); - current = result.remove(); - assertEquals(current.getToken(), IgnoreLineParser.Token.TEXT); - assertEquals(current.getValue(), "abcd"); - current = result.remove(); - assertEquals(current.getToken(), IgnoreLineParser.Token.PATH_DELIM); - current = result.remove(); - assertEquals(current.getToken(), IgnoreLineParser.Token.MATCH_ALL); - current = result.remove(); - assertEquals(current.getToken(), IgnoreLineParser.Token.PATH_DELIM); - current = result.remove(); - assertEquals(current.getToken(), IgnoreLineParser.Token.TEXT); - assertEquals(current.getValue(), "foo"); - current = result.remove(); - assertEquals(current.getToken(), IgnoreLineParser.Token.PATH_DELIM); - current = result.remove(); - assertEquals(current.getToken(), IgnoreLineParser.Token.TEXT); - assertEquals(current.getValue(), "bar"); - current = result.remove(); - assertEquals(current.getToken(), IgnoreLineParser.Token.PATH_DELIM); - current = result.remove(); - assertEquals(current.getToken(), IgnoreLineParser.Token.TEXT); - assertEquals(current.getValue(), "sample.txt"); - } - - @Test(expectedExceptions = ParserException.class, - expectedExceptionsMessageRegExp = "The pattern \\*\\*\\* is invalid\\.") - public void parseTripleStarPattern() throws Exception { - // Arrange - final String input = "should/throw/***/anywhere"; - - // Act - List result = IgnoreLineParser.parse(input); - - // Assert - fail("Expected pattern containing '***' to throw a ParserException."); - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/rules/RootedFileRuleTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/rules/RootedFileRuleTest.java deleted file mode 100644 index 920480a25572..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/ignore/rules/RootedFileRuleTest.java +++ /dev/null @@ -1,285 +0,0 @@ -package org.openapitools.codegen.ignore.rules; - -import org.testng.annotations.Test; - -import java.util.Arrays; -import java.util.List; - -import static org.testng.Assert.*; - -public class RootedFileRuleTest { - @Test - public void testMatchFilenameOnly() throws Exception { - // Arrange - final String definition = "/foo"; - final String relativePath = "foo"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo") - ); - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertTrue(actual); - } - - @Test - public void testNonMatchFilenameOnly() throws Exception { - // Arrange - final String definition = "/foo"; - final String relativePath = "bar"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo") - ); - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertFalse(actual); - } - - @Test - public void testMatchFilenameAndExtension() throws Exception { - // Arrange - final String definition = "/foo.txt"; - final String relativePath = "foo.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo.txt") - ); - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertTrue(actual); - } - - @Test - public void testNonMatchFilenameAndExtension() throws Exception { - // Arrange - final String definition = "/foo.txt"; - final String relativePath = "bar.baz"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo.txt") - ); - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertFalse(actual); - } - - @Test - public void testMatchFilenameWithGlob() throws Exception { - // Arrange - final String definition = "/foo*"; - final String relativePath = "foobarbaz"; - - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY) - ); - - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertTrue(actual); - } - - @Test - public void testNonMatchFilenameWithGlob() throws Exception { - // Arrange - final String definition = "/foo*"; - final String relativePath = "boobarbaz"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY) - ); - - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertFalse(actual); - } - - @Test - public void testMatchFilenameAndExtensionWithFilenameGlob() throws Exception { - // Arrange - final String definition = "/foo*.txt"; - final String relativePath = "foobarbaz.txt"; - - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".txt") - ); - - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertTrue(actual); - } - - @Test - public void testNonMatchFilenameAndExtensionWithFilenameGlob() throws Exception { - // Arrange - final String definition = "/foo*qux.txt"; - final String relativePath = "foobarbaz.txt"; - - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, "qux.txt") - ); - - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertFalse(actual); - } - - @Test - public void testMatchFilenameAndExtensionWithExtensionGlob() throws Exception { - // Arrange - final String definition = "/foo.*"; - final String relativePath = "foo.bak"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo."), - new Part(IgnoreLineParser.Token.MATCH_ANY) - ); - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertTrue(actual); - } - - @Test - public void testMatchFilenameAndExtensionWithMultiplePeriods() throws Exception { - // Arrange - final String definition = "/foo*.xyzzy.txt"; - final String relativePath = "foo.bar.baz.xyzzy.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt") - ); - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertTrue(actual); - } - - @Test - public void testNonMatchFilenameAndExtensionWithMultiplePeriods() throws Exception { - // Arrange - final String definition = "/foo*.xyzzy.txt"; - final String relativePath = "foo.bar.baz.qux.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt") - ); - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertFalse(actual); - } - - @Test - public void testMatchWithoutLeadingForwardSlash() throws Exception { - // Arrange - final String definition = "foo*.xyzzy.txt"; - final String relativePath = "foo.bar.baz.xyzzy.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt") - ); - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertTrue(actual); - } - - @Test - public void testMatchesOnlyRooted() throws Exception { - // Arrange - final String definition = "/path/to/some/foo*.xyzzy.txt"; - final String relativePath = "foo.bar.baz.xyzzy.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "path"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "to"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "some"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "oo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt") - ); - Rule rule = new RootedFileRule(syntax, definition); - Boolean actual = null; - - // Act - actual = rule.matches(relativePath); - - // Assert - assertFalse(actual); - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java deleted file mode 100644 index c6ee9e1c01e4..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.openapitools.codegen.inflector; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.java.JavaClientOptionsTest; -import org.openapitools.codegen.languages.JavaInflectorServerCodegen; -import org.openapitools.codegen.options.JavaInflectorServerOptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class JavaInflectorServerOptionsTest extends AbstractOptionsTest { - - @Tested - private JavaInflectorServerCodegen clientCodegen; - - public JavaInflectorServerOptionsTest() { - super(new JavaInflectorServerOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(JavaInflectorServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaInflectorServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaInflectorServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JavaInflectorServerOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JavaInflectorServerOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JavaInflectorServerOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JavaInflectorServerOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(JavaInflectorServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaInflectorServerOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(JavaInflectorServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaInflectorServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setSerializeBigDecimalAsString(true); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java deleted file mode 100644 index 1f0eda73f225..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.openapitools.codegen.java; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.languages.AbstractJavaCodegen; -import io.swagger.models.*; -import io.swagger.models.parameters.*; - -public class AbstractJavaCodegenTest { - - private final AbstractJavaCodegen fakeJavaCodegen = new AbstractJavaCodegen() { - @Override - public CodegenType getTag() { - return null; - } - - @Override - public String getName() { - return null; - } - - @Override - public String getHelp() { - return null; - } - }; - - @Test - public void toEnumVarNameShouldNotShortenUnderScore() throws Exception { - Assert.assertEquals("UNDERSCORE", fakeJavaCodegen.toEnumVarName("_", "String")); - Assert.assertEquals("__", fakeJavaCodegen.toEnumVarName("__", "String")); - Assert.assertEquals("__", fakeJavaCodegen.toEnumVarName("_,.", "String")); - } - - @Test - public void toVarNameShouldAvoidOverloadingGetClassMethod() throws Exception { - Assert.assertEquals("propertyClass", fakeJavaCodegen.toVarName("class")); - Assert.assertEquals("propertyClass", fakeJavaCodegen.toVarName("_class")); - Assert.assertEquals("propertyClass", fakeJavaCodegen.toVarName("__class")); - } - - @Test - public void toModelNameShouldUseProvidedMapping() throws Exception { - fakeJavaCodegen.importMapping().put("json_myclass", "com.test.MyClass"); - Assert.assertEquals("com.test.MyClass", fakeJavaCodegen.toModelName("json_myclass")); - } - - @Test - public void toModelNameUsesPascalCase() throws Exception { - Assert.assertEquals("JsonAnotherclass", fakeJavaCodegen.toModelName("json_anotherclass")); - } - - @Test - public void preprocessSwaggerWithFormParamsSetsContentType() { - Path dummyPath = new Path() - .post(new Operation().parameter(new FormParameter())) - .get(new Operation()); - - Swagger swagger = new Swagger() - .path("dummy", dummyPath); - - fakeJavaCodegen.preprocessSwagger(swagger); - - Assert.assertNull(swagger.getPath("dummy").getGet().getVendorExtensions().get("x-contentType")); - Assert.assertEquals(swagger.getPath("dummy").getPost().getVendorExtensions().get("x-contentType"), "application/x-www-form-urlencoded"); - } - - @Test - public void preprocessSwaggerWithBodyParamsSetsContentType() { - Path dummyPath = new Path() - .post(new Operation().parameter(new BodyParameter())) - .get(new Operation()); - - Swagger swagger = new Swagger() - .path("dummy", dummyPath); - - fakeJavaCodegen.preprocessSwagger(swagger); - - Assert.assertNull(swagger.getPath("dummy").getGet().getVendorExtensions().get("x-contentType")); - Assert.assertEquals(swagger.getPath("dummy").getPost().getVendorExtensions().get("x-contentType"), "application/json"); - } - - @Test - public void preprocessSwaggerWithNoFormOrBodyParamsDoesNotSetContentType() { - Path dummyPath = new Path() - .post(new Operation()) - .get(new Operation()); - - Swagger swagger = new Swagger() - .path("dummy", dummyPath); - - fakeJavaCodegen.preprocessSwagger(swagger); - - Assert.assertNull(swagger.getPath("dummy").getGet().getVendorExtensions().get("x-contentType")); - Assert.assertNull(swagger.getPath("dummy").getPost().getVendorExtensions().get("x-contentType")); - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java deleted file mode 100644 index 5d4bd86df2b4..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.openapitools.codegen.java; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.options.JavaClientOptionsProvider; -import org.openapitools.codegen.languages.JavaClientCodegen; -import org.openapitools.codegen.options.OptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class JavaClientOptionsTest extends AbstractOptionsTest { - - @Tested - private JavaClientCodegen clientCodegen; - - public JavaClientOptionsTest() { - super(new JavaClientOptionsProvider()); - } - - protected JavaClientOptionsTest(OptionsProvider optionsProvider) { - super(optionsProvider); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(JavaClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JavaClientOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JavaClientOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JavaClientOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JavaClientOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setArtifactUrl(JavaClientOptionsProvider.ARTIFACT_URL_VALUE); - times = 1; - clientCodegen.setArtifactDescription(JavaClientOptionsProvider.ARTIFACT_DESCRIPTION_VALUE); - times = 1; - clientCodegen.setScmConnection(JavaClientOptionsProvider.SCM_CONNECTION_VALUE); - times = 1; - clientCodegen.setScmDeveloperConnection(JavaClientOptionsProvider.SCM_DEVELOPER_CONNECTION_VALUE); - times = 1; - clientCodegen.setScmUrl(JavaClientOptionsProvider.SCM_URL_VALUE); - times = 1; - clientCodegen.setDeveloperName(JavaClientOptionsProvider.DEVELOPER_NAME_VALUE); - times = 1; - clientCodegen.setDeveloperEmail(JavaClientOptionsProvider.DEVELOPER_EMAIL_VALUE); - times = 1; - clientCodegen.setDeveloperOrganization(JavaClientOptionsProvider.DEVELOPER_ORGANIZATION_VALUE); - times = 1; - clientCodegen.setDeveloperOrganizationUrl(JavaClientOptionsProvider.DEVELOPER_ORGANIZATION_URL_VALUE); - times = 1; - clientCodegen.setLicenseName(JavaClientOptionsProvider.LICENSE_NAME_VALUE); - times = 1; - clientCodegen.setLicenseUrl(JavaClientOptionsProvider.LICENSE_URL_VALUE); - times = 1; - clientCodegen.setSourceFolder(JavaClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaClientOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(JavaClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setLibrary(JavaClientOptionsProvider.DEFAULT_LIBRARY_VALUE); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaClientOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaClientOptionsProvider.USE_BEANVALIDATION)); - times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaClientOptionsProvider.PERFORM_BEANVALIDATION)); - times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaClientOptionsProvider.PERFORM_BEANVALIDATION)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java deleted file mode 100644 index e2fe06476e9e..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.openapitools.codegen.java; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.JavaClientCodegen; -import io.swagger.models.ComposedModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.RefModel; -import io.swagger.models.properties.StringProperty; - -import com.google.common.collect.Sets; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public class JavaInheritanceTest { - - @SuppressWarnings("static-method") - @Test(description = "convert a composed model with parent") - public void javaInheritanceTest() { - final Model model = new ComposedModel().parent(new RefModel("Base")) - .child(new ModelImpl().additionalProperties(new StringProperty())); - - final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.parent, "Base"); - Assert.assertEquals(cm.imports, Sets.newHashSet("Base")); - } - - @SuppressWarnings("static-method") - @Test(description = "convert a composed model with discriminator") - public void javaInheritanceWithDiscriminatorTest() { - ModelImpl base = new ModelImpl(); - base.setDiscriminator("disc"); - - final Model model = new ComposedModel() - .interfaces(Arrays.asList(new RefModel("Base"))) - .child(new ModelImpl().additionalProperties(new StringProperty())); - - final Map allDefinitions = new HashMap(); - allDefinitions.put("Base", base); - - final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model, allDefinitions); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.parent, "Base"); - Assert.assertEquals(cm.imports, Sets.newHashSet("Base")); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java deleted file mode 100644 index 992fc4d6ae64..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.openapitools.codegen.java; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.JavaClientCodegen; -import io.swagger.models.ComposedModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.RefModel; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -@SuppressWarnings("static-method") -public class JavaModelEnumTest { - - @Test(description = "convert a java model with an enum") - public void converterTest() { - final StringProperty enumProperty = new StringProperty(); - enumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); - final ModelImpl model = new ModelImpl().property("name", enumProperty); - - final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty enumVar = cm.vars.get(0); - Assert.assertEquals(enumVar.baseName, "name"); - Assert.assertEquals(enumVar.datatype, "String"); - Assert.assertEquals(enumVar.datatypeWithEnum, "NameEnum"); - Assert.assertEquals(enumVar.name, "name"); - Assert.assertEquals(enumVar.defaultValue, "null"); - Assert.assertEquals(enumVar.baseType, "String"); - Assert.assertTrue(enumVar.isEnum); - } - - @Test(description = "not override identical parent enums") - public void overrideEnumTest() { - final StringProperty identicalEnumProperty = new StringProperty(); - identicalEnumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); - - final StringProperty subEnumProperty = new StringProperty(); - subEnumProperty.setEnum(Arrays.asList("SUB1", "SUB2", "SUB3")); - - // Add one enum property to the parent - final Map parentProperties = new HashMap(); - parentProperties.put("sharedThing", identicalEnumProperty); - - // Add TWO enums to the subType model; one of which is identical to the one in parent class - final Map subProperties = new HashMap(); - subProperties.put("sharedThing", identicalEnumProperty); - subProperties.put("unsharedThing", identicalEnumProperty); - - final ModelImpl parentModel = new ModelImpl(); - parentModel.setProperties(parentProperties); - parentModel.name("parentModel"); - - final ModelImpl subModel = new ModelImpl(); - subModel.setProperties(subProperties); - subModel.name("subModel"); - - final ComposedModel model = new ComposedModel() - .parent(new RefModel(parentModel.getName())) - .child(subModel) - .interfaces(new ArrayList()); - - final DefaultCodegen codegen = new JavaClientCodegen(); - final Map allModels = new HashMap(); - allModels.put(parentModel.getName(), parentModel); - allModels.put(subModel.getName(), subModel); - - final CodegenModel cm = codegen.fromModel("sample", model, allModels); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.parent, "ParentModel"); - Assert.assertTrue(cm.imports.contains("ParentModel")); - - // Assert that only the unshared/uninherited enum remains - Assert.assertEquals(cm.vars.size(), 1); - final CodegenProperty enumVar = cm.vars.get(0); - Assert.assertEquals(enumVar.baseName, "unsharedThing"); - Assert.assertEquals(enumVar.datatype, "String"); - Assert.assertEquals(enumVar.datatypeWithEnum, "UnsharedThingEnum"); - Assert.assertTrue(enumVar.isEnum); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java deleted file mode 100644 index 8fcecf651695..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.openapitools.codegen.java.jaxrs; - -import org.openapitools.codegen.CodegenParameter; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.samskivert.mustache.Mustache; -import com.samskivert.mustache.Template; -import org.apache.commons.io.IOUtils; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; - -public class AllowableValuesTest { - - private static final String TEMPLATE_FILE = "JavaJaxRS/allowableValues.mustache"; - private static final String PROVIDER_NAME = "operations"; - - private static String loadClassResource(Class cls, String name) throws IOException { - InputStream in = null; - try { - in = cls.getClassLoader().getResourceAsStream(name); - return IOUtils.toString(in, StandardCharsets.UTF_8); - } finally { - IOUtils.closeQuietly(in); - } - } - - @DataProvider(name = PROVIDER_NAME) - private static Object[][] resource() { - final CodegenParameter param1 = new CodegenParameter(); - final CodegenParameter param2 = new CodegenParameter() {{ - allowableValues = ImmutableMap.of("values", ImmutableList.of("item1", "item2", "item3")); - }}; - final CodegenParameter param3 = new CodegenParameter() {{ - allowableValues = ImmutableMap.of("min", 1, "max", 10); - }}; - final CodegenParameter param4 = new CodegenParameter() {{ - allowableValues = ImmutableMap.of("min", 1); - }}; - final CodegenParameter param5 = new CodegenParameter() {{ - allowableValues = ImmutableMap.of("max", 10); - }}; - - return new Object[][]{ - {param1, ""}, - {param2, "allowableValues=\"item1, item2, item3\""}, - {param3, "allowableValues=\"range=[1, 10]\""}, - {param4, "allowableValues=\"range=[1, infinity]\""}, - {param5, "allowableValues=\"range=[-infinity, 10]\""}, - }; - } - - @Test(dataProvider = PROVIDER_NAME) - public void annotationsTest(CodegenParameter parameter, String expected) throws IOException { - final Template template = Mustache.compiler().compile(loadClassResource(this.getClass(), TEMPLATE_FILE)); - - Assert.assertEquals(template.execute(parameter), expected); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/javaPlayFramework/JavaPlayFrameworkOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/javaPlayFramework/JavaPlayFrameworkOptionsTest.java deleted file mode 100644 index 781170f795cc..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/javaPlayFramework/JavaPlayFrameworkOptionsTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.openapitools.codegen.javaPlayFramework; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.JavaPlayFrameworkCodegen; -import org.openapitools.codegen.options.JavaPlayFrameworkOptionsProvider; -import org.openapitools.codegen.options.OptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class JavaPlayFrameworkOptionsTest extends AbstractOptionsTest { - - @Tested - private JavaPlayFrameworkCodegen clientCodegen; - - public JavaPlayFrameworkOptionsTest() { - super(new JavaPlayFrameworkOptionsProvider()); - } - - protected JavaPlayFrameworkOptionsTest(OptionsProvider optionsProvider) { - super(optionsProvider); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(JavaPlayFrameworkOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaPlayFrameworkOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaPlayFrameworkOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JavaPlayFrameworkOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JavaPlayFrameworkOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JavaPlayFrameworkOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JavaPlayFrameworkOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(JavaPlayFrameworkOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaPlayFrameworkOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(JavaPlayFrameworkOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaPlayFrameworkOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setTitle(JavaPlayFrameworkOptionsProvider.TITLE); - times = 1; - clientCodegen.setConfigPackage(JavaPlayFrameworkOptionsProvider.CONFIG_PACKAGE_VALUE); - times = 1; - clientCodegen.setBasePackage(JavaPlayFrameworkOptionsProvider.BASE_PACKAGE_VALUE); - times = 1; - clientCodegen.setControllerOnly(Boolean.valueOf(JavaPlayFrameworkOptionsProvider.CONTROLLER_ONLY)); - times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaPlayFrameworkOptionsProvider.USE_BEANVALIDATION)); - times = 1; - clientCodegen.setUseInterfaces(Boolean.valueOf(JavaPlayFrameworkOptionsProvider.USE_INTERFACES)); - times = 1; - clientCodegen.setHandleExceptions(Boolean.valueOf(JavaPlayFrameworkOptionsProvider.HANDLE_EXCEPTIONS)); - times = 1; - clientCodegen.setWrapCalls(Boolean.valueOf(JavaPlayFrameworkOptionsProvider.WRAP_CALLS)); - times = 1; - clientCodegen.setUseSwaggerUI(Boolean.valueOf(JavaPlayFrameworkOptionsProvider.USE_SWAGGER_UI)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptClientOptionsTest.java deleted file mode 100644 index 7c3de57cff4d..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptClientOptionsTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.openapitools.codegen.javascript; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.options.JavaScriptOptionsProvider; -import org.openapitools.codegen.languages.JavascriptClientCodegen; -import org.openapitools.codegen.options.OptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class JavaScriptClientOptionsTest extends AbstractOptionsTest { - @Tested - private JavascriptClientCodegen clientCodegen; - - public JavaScriptClientOptionsTest() { - super(new JavaScriptOptionsProvider()); - } - - protected JavaScriptClientOptionsTest(OptionsProvider optionsProvider) { - super(optionsProvider); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @Override - protected void setExpectations() { - // Commented generic options not yet supported by JavaScript codegen. - new Expectations(clientCodegen) {{ - clientCodegen.setInvokerPackage(JavaScriptOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setModelPackage(JavaScriptOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaScriptOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaScriptOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; -// clientCodegen.setInvokerPackage(JavaScriptOptionsProvider.INVOKER_PACKAGE_VALUE); -// times = 1; -// clientCodegen.setGroupId(JavaScriptOptionsProvider.GROUP_ID_VALUE); -// times = 1; -// clientCodegen.setArtifactId(JavaScriptOptionsProvider.ARTIFACT_ID_VALUE); -// times = 1; -// clientCodegen.setArtifactVersion(JavaScriptOptionsProvider.ARTIFACT_VERSION_VALUE); -// times = 1; - clientCodegen.setSourceFolder(JavaScriptOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaScriptOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setProjectName(JavaScriptOptionsProvider.PROJECT_NAME_VALUE); - times = 1; - clientCodegen.setModuleName(JavaScriptOptionsProvider.MODULE_NAME_VALUE); - times = 1; - clientCodegen.setProjectDescription(JavaScriptOptionsProvider.PROJECT_DESCRIPTION_VALUE); - times = 1; - clientCodegen.setProjectVersion(JavaScriptOptionsProvider.PROJECT_VERSION_VALUE); - times = 1; - clientCodegen.setLicenseName(JavaScriptOptionsProvider.PROJECT_LICENSE_NAME_VALUE); - times = 1; - clientCodegen.setUsePromises(Boolean.valueOf(JavaScriptOptionsProvider.USE_PROMISES_VALUE)); - times = 1; - clientCodegen.setUseInheritance(Boolean.valueOf(JavaScriptOptionsProvider.USE_INHERITANCE_VALUE)); - times = 1; - clientCodegen.setEmitModelMethods(Boolean.valueOf(JavaScriptOptionsProvider.EMIT_MODEL_METHODS_VALUE)); - times = 1; - clientCodegen.setEmitJSDoc(Boolean.valueOf(JavaScriptOptionsProvider.EMIT_JS_DOC_VALUE)); - times = 1; - clientCodegen.setUseES6(Boolean.valueOf(JavaScriptOptionsProvider.USE_ES6_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java deleted file mode 100644 index 5794a4cfdcc0..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.openapitools.codegen.javascript; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.collect.Sets; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.languages.JavascriptClientCodegen; -import io.swagger.models.ComposedModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.RefModel; -import io.swagger.models.properties.StringProperty; - -public class JavaScriptInheritanceTest { - @SuppressWarnings("static-method") - @Test(description = "convert a composed model with inheritance enabled") - public void javascriptInheritanceTest() { - ModelImpl base = new ModelImpl(); - base.addProperty("baseProp", new StringProperty().required(true)); - ModelImpl intf1 = new ModelImpl(); - intf1.addProperty("intf1Prop", new StringProperty()); - ModelImpl intf2 = new ModelImpl(); - intf2.addProperty("intf2Prop", new StringProperty().required(true)); - ModelImpl child = new ModelImpl(); - child.addProperty("childProp", new StringProperty().required(true)); - - final Map allDefinitions = new HashMap(); - allDefinitions.put("Base", base); - allDefinitions.put("Interface1", intf1); - allDefinitions.put("Interface2", intf2); - - final Model model = new ComposedModel().parent(new RefModel("Base")) - .interfaces(Arrays.asList(new RefModel("Interface1"), new RefModel("Interface2"))) - .child(child); - - final JavascriptClientCodegen codegen = new JavascriptClientCodegen(); - codegen.setUseInheritance(true); - - final CodegenModel cm = codegen.fromModel("sample", model, allDefinitions); - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.parent, "Base"); - Assert.assertEquals(cm.interfaces, Arrays.asList("Interface1", "Interface2")); - Assert.assertEquals(cm.imports, Sets.newHashSet("Base", "Interface1", "Interface2")); - Assert.assertEquals(cm.vars.size(), 1); - Assert.assertEquals(cm.vars.get(0).name, "childProp"); - Assert.assertEquals(cm.allVars.size(), 4); - String[] allVars = {"intf1Prop", "intf2Prop", "baseProp", "childProp"}; - for (int i = 0; i < allVars.length; i++) { - Assert.assertEquals(cm.allVars.get(i).name, allVars[i]); - } - Assert.assertEquals(cm.mandatory, Sets.newHashSet("childProp")); - Assert.assertEquals(cm.allMandatory, Sets.newHashSet("baseProp", "intf2Prop", "childProp")); - } - - @SuppressWarnings("static-method") - @Test(description = "convert a composed model with inheritance disabled") - public void javascriptNoInheritanceTest() { - ModelImpl base = new ModelImpl(); - base.addProperty("baseProp", new StringProperty().required(true)); - ModelImpl intf1 = new ModelImpl(); - intf1.addProperty("intf1Prop", new StringProperty()); - ModelImpl intf2 = new ModelImpl(); - intf2.addProperty("intf2Prop", new StringProperty().required(true)); - ModelImpl child = new ModelImpl(); - child.addProperty("childProp", new StringProperty().required(true)); - - final Map allDefinitions = new HashMap(); - allDefinitions.put("Base", base); - allDefinitions.put("Interface1", intf1); - allDefinitions.put("Interface2", intf2); - - final Model model = new ComposedModel().parent(new RefModel("Base")) - .interfaces(Arrays.asList(new RefModel("Interface1"), new RefModel("Interface2"))) - .child(child); - - final JavascriptClientCodegen codegen = new JavascriptClientCodegen(); - codegen.setUseInheritance(false); - - final CodegenModel cm = codegen.fromModel("sample", model, allDefinitions); - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.parent, "Base"); - Assert.assertEquals(cm.interfaces, Arrays.asList("Interface1", "Interface2")); - Assert.assertEquals(cm.imports, Sets.newHashSet("Base", "Interface1", "Interface2")); - Assert.assertEquals(cm.vars.size(), 4); - Assert.assertEquals(cm.allVars.size(), 4); - String[] allVars = {"intf1Prop", "intf2Prop", "baseProp", "childProp"}; - for (int i = 0; i < allVars.length; i++) { - Assert.assertEquals(cm.vars.get(i).name, allVars[i]); - Assert.assertEquals(cm.allVars.get(i).name, allVars[i]); - } - Assert.assertEquals(cm.mandatory, Sets.newHashSet("baseProp", "intf2Prop", "childProp")); - Assert.assertEquals(cm.allMandatory, Sets.newHashSet("baseProp", "intf2Prop", "childProp")); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java deleted file mode 100644 index 3b04655ecfb7..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package org.openapitools.codegen.javascript; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.JavascriptClientCodegen; -import io.swagger.models.ComposedModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.RefModel; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -@SuppressWarnings("static-method") -public class JavaScriptModelEnumTest { - @Test(description = "convert a JavaScript model with an enum") - public void converterTest() { - final StringProperty enumProperty = new StringProperty(); - enumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); - final ModelImpl model = new ModelImpl().property("name", enumProperty); - - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty enumVar = cm.vars.get(0); - Assert.assertEquals(enumVar.baseName, "name"); - Assert.assertEquals(enumVar.datatype, "String"); - Assert.assertEquals(enumVar.datatypeWithEnum, "NameEnum"); - Assert.assertEquals(enumVar.name, "name"); - Assert.assertEquals(enumVar.defaultValue, null); - Assert.assertEquals(enumVar.baseType, "String"); - Assert.assertTrue(enumVar.isEnum); - } - - @Test(description = "not override identical parent enums") - public void overrideEnumTest() { - final StringProperty identicalEnumProperty = new StringProperty(); - identicalEnumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); - - final StringProperty subEnumProperty = new StringProperty(); - subEnumProperty.setEnum(Arrays.asList("SUB1", "SUB2", "SUB3")); - - // Add one enum property to the parent - final Map parentProperties = new HashMap(); - parentProperties.put("sharedThing", identicalEnumProperty); - - // Add TWO enums to the subType model; one of which is identical to the one in parent class - final Map subProperties = new HashMap(); - subProperties.put("sharedThing", identicalEnumProperty); - subProperties.put("unsharedThing", identicalEnumProperty); - - final ModelImpl parentModel = new ModelImpl(); - parentModel.setProperties(parentProperties); - parentModel.name("parentModel"); - - final ModelImpl subModel = new ModelImpl(); - subModel.setProperties(subProperties); - subModel.name("subModel"); - - final ComposedModel model = new ComposedModel() - .parent(new RefModel(parentModel.getName())) - .child(subModel) - .interfaces(new ArrayList()); - - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final Map allModels = new HashMap(); - allModels.put(parentModel.getName(), parentModel); - allModels.put(subModel.getName(), subModel); - - final CodegenModel cm = codegen.fromModel("sample", model, allModels); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.parent, "ParentModel"); - Assert.assertTrue(cm.imports.contains("ParentModel")); - - // Assert that only the unshared/uninherited enum remains - Assert.assertEquals(cm.vars.size(), 1); - final CodegenProperty enumVar = cm.vars.get(0); - Assert.assertEquals(enumVar.baseName, "unsharedThing"); - Assert.assertEquals(enumVar.datatype, "String"); - Assert.assertEquals(enumVar.datatypeWithEnum, "UnsharedThingEnum"); - Assert.assertTrue(enumVar.isEnum); - } - - @Test(description = "test enum array model") - public void enumArrayModelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final Model definition = model.getDefinitions().get("EnumArrays"); - - Property property = definition.getProperties().get("array_enum"); - CodegenProperty prope = codegen.fromProperty("array_enum", property); - codegen.updateCodegenPropertyEnum(prope); - Assert.assertEquals(prope.datatypeWithEnum, "[ArrayEnumEnum]"); - Assert.assertEquals(prope.enumName, "ArrayEnumEnum"); - Assert.assertTrue(prope.isEnum); - Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList("fish", "crab")); - - HashMap fish= new HashMap(); - fish.put("name", "fish"); - fish.put("value", "\"fish\""); - HashMap crab= new HashMap(); - crab.put("name", "crab"); - crab.put("value", "\"crab\""); - Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); - - // assert inner items - Assert.assertEquals(prope.datatypeWithEnum, "[ArrayEnumEnum]"); - Assert.assertEquals(prope.enumName, "ArrayEnumEnum"); - Assert.assertTrue(prope.items.isEnum); - Assert.assertEquals(prope.items.allowableValues.get("values"), Arrays.asList("fish", "crab")); - Assert.assertEquals(prope.items.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); - - } - - @Test(description = "test enum model for values (numeric, string, etc)") - public void enumModelValueTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final Model definition = model.getDefinitions().get("Enum_Test"); - - Property property = definition.getProperties().get("enum_integer"); - CodegenProperty prope = codegen.fromProperty("enum_integer", property); - codegen.updateCodegenPropertyEnum(prope); - Assert.assertEquals(prope.datatypeWithEnum, "EnumIntegerEnum"); - Assert.assertEquals(prope.enumName, "EnumIntegerEnum"); - Assert.assertTrue(prope.isEnum); - Assert.assertFalse(prope.isContainer); - Assert.assertNull(prope.items); - Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList(1, -1)); - - HashMap one = new HashMap(); - one.put("name", "1"); - one.put("value", "1"); - HashMap minusOne = new HashMap(); - minusOne.put("name", "-1"); - minusOne.put("value", "-1"); - Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(one, minusOne)); - - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java deleted file mode 100644 index 062f39226394..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java +++ /dev/null @@ -1,491 +0,0 @@ -package org.openapitools.codegen.javascript; - -import java.util.List; - -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import com.google.common.collect.Sets; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenParameter; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.JavascriptClientCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.parameters.QueryParameter; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.ByteArrayProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; - -@SuppressWarnings("static-method") -public class JavaScriptModelTest { - @Test(description = "convert a simple java model") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty() - .example("Tony")) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 3); - - final List vars = cm.vars; - - final CodegenProperty property1 = vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.getter, "getId"); - Assert.assertEquals(property1.setter, "setId"); - Assert.assertEquals(property1.datatype, "Number"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, null); - Assert.assertEquals(property1.baseType, "Number"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.getter, "getName"); - Assert.assertEquals(property2.setter, "setName"); - Assert.assertEquals(property2.datatype, "String"); - Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, null); - Assert.assertEquals(property2.baseType, "String"); - Assert.assertEquals(property2.example, "Tony"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.getter, "getCreatedAt"); - Assert.assertEquals(property3.setter, "setCreatedAt"); - Assert.assertEquals(property3.datatype, "Date"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, null); - Assert.assertEquals(property3.baseType, "Date"); - Assert.assertFalse(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - } - - @Test(description = "convert a model with list property") - public void listPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id"); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 2); - - final CodegenProperty property = cm.vars.get(1); - Assert.assertEquals(property.baseName, "urls"); - Assert.assertEquals(property.getter, "getUrls"); - Assert.assertEquals(property.setter, "setUrls"); - Assert.assertEquals(property.datatype, "[String]"); - Assert.assertEquals(property.name, "urls"); - // FIXME: should an array property have an empty array as its default value? What if the property is required? - Assert.assertEquals(property.defaultValue, /*"[]"*/null); - Assert.assertEquals(property.baseType, "Array"); - Assert.assertEquals(property.containerType, "array"); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isContainer); - } - - @Test(description = "convert a model with a map property") - public void mapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "translations"); - Assert.assertEquals(property.getter, "getTranslations"); - Assert.assertEquals(property.setter, "setTranslations"); - Assert.assertEquals(property.datatype, "{String: String}"); - Assert.assertEquals(property.name, "translations"); - // FIXME: should a map property have an empty object as its default value? What if the property is required? - Assert.assertEquals(property.defaultValue, /*"{}"*/null); - Assert.assertEquals(property.baseType, "Object"); - Assert.assertEquals(property.containerType, "map"); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isContainer); - } - - @Test(description = "convert a model with a map with complex list property") - public void mapWithListPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", - new MapProperty().additionalProperties(new ArrayProperty().items(new RefProperty("Pet")))) - .required("id"); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "translations"); - Assert.assertEquals(property.getter, "getTranslations"); - Assert.assertEquals(property.setter, "setTranslations"); - Assert.assertEquals(property.datatype, "{String: [Pet]}"); - Assert.assertEquals(property.name, "translations"); - // FIXME: should a map property have an empty object as its default value? What if the property is required? - Assert.assertEquals(property.defaultValue, /*"{}"*/null); - Assert.assertEquals(property.baseType, "Object"); - Assert.assertEquals(property.containerType, "map"); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isContainer); - } - - @Test(description = "convert a model with a 2D list property") - public void list2DPropertyTest() { - final Model model = new ModelImpl().name("sample").property("list2D", new ArrayProperty().items( - new ArrayProperty().items(new RefProperty("Pet")))); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "list2D"); - Assert.assertEquals(property.getter, "getList2D"); - Assert.assertEquals(property.setter, "setList2D"); - Assert.assertEquals(property.datatype, "[[Pet]]"); - Assert.assertEquals(property.name, "list2D"); - // FIXME: should an array property have an empty array as its default value? What if the property is required? - Assert.assertEquals(property.defaultValue, /*"[]"*/null); - Assert.assertEquals(property.baseType, "Array"); - Assert.assertEquals(property.containerType, "array"); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isContainer); - } - - @Test(description = "convert a model with complex properties") - public void complexPropertiesTest() { - final Model model = new ModelImpl().description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "children"); - Assert.assertEquals(property.getter, "getChildren"); - Assert.assertEquals(property.setter, "setChildren"); - Assert.assertEquals(property.datatype, "Children"); - Assert.assertEquals(property.name, "children"); - Assert.assertEquals(property.defaultValue, null); - Assert.assertEquals(property.baseType, "Children"); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isNotContainer); - } - - @Test(description = "convert a model with complex list property") - public void complexListPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty().items(new RefProperty("#/definitions/Children"))); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "children"); - Assert.assertEquals(property.complexType, "Children"); - Assert.assertEquals(property.getter, "getChildren"); - Assert.assertEquals(property.setter, "setChildren"); - // FIXME: what should datatype be for a JavaScript array? -// Assert.assertEquals(property.datatype, "Array"); - Assert.assertEquals(property.name, "children"); - // FIXME: should an array property have an empty array as its default value? What if the property is required? - Assert.assertEquals(property.defaultValue, /*"[]"*/null); - Assert.assertEquals(property.baseType, "Array"); - Assert.assertEquals(property.containerType, "array"); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isContainer); - } - - @Test(description = "convert a model with complex map property") - public void complexMapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty().additionalProperties(new RefProperty("#/definitions/Children"))); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "children"); - Assert.assertEquals(property.complexType, "Children"); - Assert.assertEquals(property.getter, "getChildren"); - Assert.assertEquals(property.setter, "setChildren"); - // TODO: create a functional test to see whether map properties actually work. - Assert.assertEquals(property.datatype, /*"Object"*/"{String: Children}"); - Assert.assertEquals(property.name, "children"); - // FIXME: should a map property have an empty object as its default value? What if the property is required? - Assert.assertEquals(property.defaultValue, /*"{}"*/ null); - Assert.assertEquals(property.baseType, "Object"); - Assert.assertEquals(property.containerType, "map"); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isContainer); - Assert.assertFalse(property.isNotContainer); - } - - @Test(description = "convert an array model") - public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "an array model"); - Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.parent, "Array"); - Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - } - - @Test(description = "convert a map model") - public void mapModelTest() { - final Model model = new ModelImpl() - .description("an map model") - .additionalProperties(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "an map model"); - Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.parent, "Object"); - Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - } - - @Test(description = "convert a model with uppercase property names") - public void upperCaseNamesTest() { - final Model model = new ModelImpl() - .description("a model with uppercase property names") - .property("NAME", new StringProperty()) - .required("NAME"); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "NAME"); - Assert.assertEquals(property.getter, "getNAME"); - Assert.assertEquals(property.setter, "setNAME"); - Assert.assertEquals(property.datatype, "String"); - Assert.assertEquals(property.name, "NAME"); - Assert.assertEquals(property.defaultValue, null); - Assert.assertEquals(property.baseType, "String"); - Assert.assertFalse(property.hasMore); - Assert.assertTrue(property.required); - Assert.assertTrue(property.isNotContainer); - } - - @Test(description = "convert a model with a 2nd char uppercase property names") - public void secondCharUpperCaseNamesTest() { - final Model model = new ModelImpl() - .description("a model with a 2nd char uppercase property names") - .property("pId", new StringProperty()) - .required("pId"); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "pId"); - Assert.assertEquals(property.getter, "getPId"); - Assert.assertEquals(property.setter, "setPId"); - Assert.assertEquals(property.datatype, "String"); - Assert.assertEquals(property.name, "pId"); - Assert.assertEquals(property.defaultValue, null); - Assert.assertEquals(property.baseType, "String"); - Assert.assertFalse(property.hasMore); - Assert.assertTrue(property.required); - Assert.assertTrue(property.isNotContainer); - } - - @Test(description = "convert hyphens per issue 503") - public void hyphensTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("created-at", new DateTimeProperty()); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "created-at"); - Assert.assertEquals(property.getter, "getCreatedAt"); - Assert.assertEquals(property.setter, "setCreatedAt"); - Assert.assertEquals(property.name, "createdAt"); - } - - @Test(description = "convert query[password] to queryPassword") - public void squareBracketsTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("query[password]", new StringProperty()); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "query[password]"); - Assert.assertEquals(property.getter, "getQueryPassword"); - Assert.assertEquals(property.setter, "setQueryPassword"); - Assert.assertEquals(property.name, "queryPassword"); - } - - @Test(description = "properly escape names per 567") - public void escapeNamesTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("created-at", new DateTimeProperty()); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("with.dots", model); - - Assert.assertEquals(cm.classname, "WithDots"); - } - - @Test(description = "convert a model with binary data") - public void binaryDataTest() { - final Model model = new ModelImpl() - .description("model with binary") - .property("inputBinaryData", new ByteArrayProperty()); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "inputBinaryData"); - Assert.assertEquals(property.getter, "getInputBinaryData"); - Assert.assertEquals(property.setter, "setInputBinaryData"); - Assert.assertEquals(property.datatype, "Blob"); - Assert.assertEquals(property.name, "inputBinaryData"); - Assert.assertEquals(property.defaultValue, null); - Assert.assertEquals(property.baseType, "Blob"); - Assert.assertFalse(property.hasMore); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isNotContainer); - } - - @Test(description = "translate an invalid param name") - public void invalidParamNameTest() { - final Model model = new ModelImpl() - .description("a model with a 2nd char uppercase property name") - .property("_", new StringProperty()); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.baseName, "_"); - Assert.assertEquals(property.getter, "getU"); - Assert.assertEquals(property.setter, "setU"); - Assert.assertEquals(property.datatype, "String"); - Assert.assertEquals(property.name, "u"); - Assert.assertEquals(property.defaultValue, null); - Assert.assertEquals(property.baseType, "String"); - Assert.assertFalse(property.hasMore); - Assert.assertTrue(property.isNotContainer); - } - - @Test(description = "convert a parameter") - public void convertParameterTest() { - final QueryParameter parameter = new QueryParameter() - .property(new IntegerProperty()) - .name("limit") - .required(true); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenParameter cm = codegen.fromParameter(parameter, null); - - Assert.assertNull(cm.allowableValues); - } - - @DataProvider(name = "modelNames") - public static Object[][] primeNumbers() { - return new Object[][] { - {"sample", "Sample"}, - {"sample_name", "SampleName"}, - {"sample__name", "SampleName"}, - {"/sample", "Sample"}, - {"\\sample", "Sample"}, - {"sample.name", "SampleName"}, - {"_sample", "Sample"}, - {"Sample", "Sample"}, - }; - } - - @Test(dataProvider = "modelNames", description = "avoid inner class") - public void modelNameTest(String name, String expectedName) { - final Model model = new ModelImpl(); - final DefaultCodegen codegen = new JavascriptClientCodegen(); - final CodegenModel cm = codegen.fromModel(name, model); - - Assert.assertEquals(cm.name, name); - Assert.assertEquals(cm.classname, expectedName); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyEapServerOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyEapServerOptionsTest.java deleted file mode 100644 index a9b7d0db04cd..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyEapServerOptionsTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.openapitools.codegen.jaxrs; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.JavaResteasyEapServerCodegen; -import org.openapitools.codegen.options.JavaResteasyEapServerOptionsProvider; -import org.openapitools.codegen.options.OptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class JavaResteasyEapServerOptionsTest extends AbstractOptionsTest { - - @Tested - private JavaResteasyEapServerCodegen clientCodegen; - - public JavaResteasyEapServerOptionsTest() { - super(new JavaResteasyEapServerOptionsProvider()); - } - - protected JavaResteasyEapServerOptionsTest(OptionsProvider optionsProvider) { - super(optionsProvider); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @Override - protected void setExpectations() { - new Expectations(clientCodegen) { - { - clientCodegen.setModelPackage(JavaResteasyEapServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaResteasyEapServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag( - Boolean.valueOf(JavaResteasyEapServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JavaResteasyEapServerOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JavaResteasyEapServerOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JavaResteasyEapServerOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JavaResteasyEapServerOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(JavaResteasyEapServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaResteasyEapServerOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel( - Boolean.valueOf(JavaResteasyEapServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen - .setFullJavaUtil(Boolean.valueOf(JavaResteasyEapServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setSerializeBigDecimalAsString(true); - times = 1; - - clientCodegen.setGenerateJbossDeploymentDescriptor( - Boolean.valueOf(JavaResteasyEapServerOptionsProvider.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)); - times = 1; - - // no invocation as it is already defined as true in JavaResteasyEapServerCodegen - // clientCodegen - // .setUseBeanValidation(Boolean.valueOf(JavaResteasyEapServerOptionsProvider.USE_BEANVALIDATION)); - // times = 1; - clientCodegen - .setUseSwaggerFeature( - Boolean.valueOf(JavaResteasyEapServerOptionsProvider.USE_SWAGGER_FEATURE)); - times = 1; - - } - }; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java deleted file mode 100644 index a87a3d0947ac..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.openapitools.codegen.jaxrs; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.JavaResteasyServerCodegen; -import org.openapitools.codegen.options.JavaResteasyServerOptionsProvider; -import org.openapitools.codegen.options.OptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class JavaResteasyServerOptionsTest extends AbstractOptionsTest { - - @Tested - private JavaResteasyServerCodegen clientCodegen; - - public JavaResteasyServerOptionsTest() { - super(new JavaResteasyServerOptionsProvider()); - } - - protected JavaResteasyServerOptionsTest(OptionsProvider optionsProvider) { - super(optionsProvider); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @Override - protected void setExpectations() { - new Expectations(clientCodegen) { - { - clientCodegen.setModelPackage(JavaResteasyServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaResteasyServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag( - Boolean.valueOf(JavaResteasyServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JavaResteasyServerOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JavaResteasyServerOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JavaResteasyServerOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JavaResteasyServerOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(JavaResteasyServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaResteasyServerOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel( - Boolean.valueOf(JavaResteasyServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaResteasyServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setSerializeBigDecimalAsString(true); - times = 1; - - clientCodegen.setGenerateJbossDeploymentDescriptor( - Boolean.valueOf(JavaResteasyServerOptionsProvider.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)); - - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaResteasyServerOptionsProvider.USE_BEANVALIDATION)); - times = 1; - - } - }; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java deleted file mode 100644 index df366a141864..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.openapitools.codegen.jaxrs; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.java.JavaClientOptionsTest; -import org.openapitools.codegen.languages.JavaJerseyServerCodegen; -import org.openapitools.codegen.options.JaxRSServerOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class JaxRSServerOptionsTest extends AbstractOptionsTest { - - @Tested - private JavaJerseyServerCodegen clientCodegen; - - public JaxRSServerOptionsTest() { - super(new JaxRSServerOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(JaxRSServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JaxRSServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JaxRSServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JaxRSServerOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JaxRSServerOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JaxRSServerOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JaxRSServerOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setArtifactUrl(JaxRSServerOptionsProvider.ARTIFACT_URL_VALUE); - times = 1; - clientCodegen.setArtifactDescription(JaxRSServerOptionsProvider.ARTIFACT_DESCRIPTION_VALUE); - times = 1; - clientCodegen.setScmConnection(JaxRSServerOptionsProvider.SCM_CONNECTION_VALUE); - times = 1; - clientCodegen.setScmDeveloperConnection(JaxRSServerOptionsProvider.SCM_DEVELOPER_CONNECTION_VALUE); - times = 1; - clientCodegen.setScmUrl(JaxRSServerOptionsProvider.SCM_URL_VALUE); - times = 1; - clientCodegen.setDeveloperName(JaxRSServerOptionsProvider.DEVELOPER_NAME_VALUE); - times = 1; - clientCodegen.setDeveloperEmail(JaxRSServerOptionsProvider.DEVELOPER_EMAIL_VALUE); - times = 1; - clientCodegen.setDeveloperOrganization(JaxRSServerOptionsProvider.DEVELOPER_ORGANIZATION_VALUE); - times = 1; - clientCodegen.setDeveloperOrganizationUrl(JaxRSServerOptionsProvider.DEVELOPER_ORGANIZATION_URL_VALUE); - times = 1; - clientCodegen.setSourceFolder(JaxRSServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JaxRSServerOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(JaxRSServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - //clientCodegen.setLibrary(JaxRSServerOptionsProvider.JAXRS_LIBRARY_VALUE); - clientCodegen.setLibrary("jersey1"); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JaxRSServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setDateLibrary("joda"); - times = 1; - clientCodegen.setSupportJava6(false); - times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(JaxRSServerOptionsProvider.USE_BEANVALIDATION)); - times = 1; - clientCodegen.setUseTags(Boolean.valueOf(JaxRSServerOptionsProvider.USE_TAGS)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFClientOptionsTest.java deleted file mode 100644 index c573ea73d8bf..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFClientOptionsTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.openapitools.codegen.jaxrs; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.JavaCXFClientCodegen; -import org.openapitools.codegen.options.JavaCXFClientOptionsProvider; -import org.openapitools.codegen.options.OptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class JaxrsCXFClientOptionsTest extends AbstractOptionsTest { - - @Tested - private JavaCXFClientCodegen clientCodegen; - - public JaxrsCXFClientOptionsTest() { - super(new JavaCXFClientOptionsProvider()); - } - - protected JaxrsCXFClientOptionsTest(OptionsProvider optionsProvider) { - super(optionsProvider); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @Override - protected void setExpectations() { - new Expectations(clientCodegen) { - { - clientCodegen.setModelPackage(JavaCXFClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaCXFClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen - .setSortParamsByRequiredFlag(Boolean.valueOf(JavaCXFClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JavaCXFClientOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JavaCXFClientOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JavaCXFClientOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JavaCXFClientOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(JavaCXFClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaCXFClientOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen - .setSerializableModel(Boolean.valueOf(JavaCXFClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaCXFClientOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setSerializeBigDecimalAsString(true); - times = 1; - - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaCXFClientOptionsProvider.USE_BEANVALIDATION)); - times = 1; - clientCodegen.setUseGenericResponse(Boolean.valueOf(JavaCXFClientOptionsProvider.USE_GENERIC_RESPONSE)); - times = 1; - - clientCodegen.setUseLoggingFeatureForTests( - Boolean.valueOf(JavaCXFClientOptionsProvider.USE_LOGGING_FEATURE_FOR_TESTS)); - times = 1; - - } - }; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFServerOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFServerOptionsTest.java deleted file mode 100644 index c1f5a320561a..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFServerOptionsTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.openapitools.codegen.jaxrs; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.JavaCXFServerCodegen; -import org.openapitools.codegen.options.JavaCXFServerOptionsProvider; -import org.openapitools.codegen.options.OptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class JaxrsCXFServerOptionsTest extends AbstractOptionsTest { - - @Tested - private JavaCXFServerCodegen clientCodegen; - - public JaxrsCXFServerOptionsTest() { - super(new JavaCXFServerOptionsProvider()); - } - - protected JaxrsCXFServerOptionsTest(OptionsProvider optionsProvider) { - super(optionsProvider); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @Override - protected void setExpectations() { - new Expectations(clientCodegen) { - { - clientCodegen.setModelPackage(JavaCXFServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaCXFServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen - .setSortParamsByRequiredFlag(Boolean.valueOf(JavaCXFServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JavaCXFServerOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JavaCXFServerOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JavaCXFServerOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JavaCXFServerOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(JavaCXFServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaCXFServerOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen - .setSerializableModel(Boolean.valueOf(JavaCXFServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaCXFServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setSerializeBigDecimalAsString(true); - times = 1; - - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_BEANVALIDATION)); - times = 1; - - clientCodegen.setGenerateSpringApplication( - Boolean.valueOf(JavaCXFServerOptionsProvider.USE_SWAGGER_FEATURE)); - times = 1; - clientCodegen.setUseWadlFeature(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_WADL_FEATURE)); - times = 1; - clientCodegen - .setUseMultipartFeature(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_MULTIPART_FEATURE)); - times = 1; - clientCodegen.setUseGzipFeature(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_GZIP_FEATURE)); - times = 1; - clientCodegen.setUseGzipFeatureForTests(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_GZIP_FEATURE)); - times = 1; - clientCodegen.setUseLoggingFeature(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_LOGGING_FEATURE)); - times = 1; - clientCodegen.setUseLoggingFeatureForTests( - Boolean.valueOf(JavaCXFServerOptionsProvider.USE_LOGGING_FEATURE_FOR_TESTS)); - times = 1; - clientCodegen.setUseBeanValidationFeature( - Boolean.valueOf(JavaCXFServerOptionsProvider.USE_BEANVALIDATION_FEATURE)); - times = 1; - clientCodegen.setUseGenericResponse(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_GENERIC_RESPONSE)); - times = 1; - - clientCodegen.setGenerateSpringBootApplication( - Boolean.valueOf(JavaCXFServerOptionsProvider.GENERATE_SPRING_BOOT_APPLICATION)); - times = 1; - - clientCodegen.setUseSpringAnnotationConfig( - Boolean.valueOf(JavaCXFServerOptionsProvider.USE_SPRING_ANNOTATION_CONFIG)); - times = 1; - - clientCodegen.setGenerateJbossDeploymentDescriptor( - Boolean.valueOf(JavaCXFServerOptionsProvider.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)); - times = 1; - - clientCodegen.setUseSwaggerUI(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_SWAGGER_UI)); - times = 1; - - clientCodegen.setAddConsumesProducesJson( - Boolean.valueOf(JavaCXFServerOptionsProvider.ADD_CONSUMES_PRODUCES_JSON)); - times = 1; - } - }; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsJava8ModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsJava8ModelTest.java deleted file mode 100644 index 11ed2282a90d..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsJava8ModelTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.openapitools.codegen.jaxrs; - -import org.openapitools.codegen.CodegenModel; - -import org.openapitools.codegen.languages.JavaJerseyServerCodegen; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.util.Json; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; - -@SuppressWarnings("static-method") -public class JaxrsJava8ModelTest { - - @Test(description = "convert a simple java model with java8 types") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("theDate", new DateProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); - - final JavaJerseyServerCodegen codegen = new JavaJerseyServerCodegen(); - codegen.setDateLibrary("java8"); - codegen.processOpts(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Json.prettyPrint(cm); - assertEquals(cm.vars.get(0).datatype, "Long"); - assertEquals(cm.vars.get(1).datatype, "LocalDate"); - assertEquals(cm.vars.get(2).datatype, "OffsetDateTime"); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsJodaModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsJodaModelTest.java deleted file mode 100644 index ec8d0a3eb8cb..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/jaxrs/JaxrsJodaModelTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.openapitools.codegen.jaxrs; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.languages.JavaJerseyServerCodegen; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.util.Json; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; - -@SuppressWarnings("static-method") -public class JaxrsJodaModelTest { - - @Test(description = "convert a simple java model with Joda types") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("theDate", new DateProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); - - final JavaJerseyServerCodegen codegen = new JavaJerseyServerCodegen(); - codegen.setDateLibrary("joda"); - codegen.processOpts(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Json.prettyPrint(cm); - assertEquals(cm.vars.get(0).datatype, "Long"); - assertEquals(cm.vars.get(1).datatype, "LocalDate"); - assertEquals(cm.vars.get(2).datatype, "DateTime"); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/kotlin/KotlinClientCodegenModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/kotlin/KotlinClientCodegenModelTest.java deleted file mode 100644 index e53b90c49a85..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/kotlin/KotlinClientCodegenModelTest.java +++ /dev/null @@ -1,255 +0,0 @@ -package org.openapitools.codegen.kotlin; - -import org.openapitools.codegen.*; -import org.openapitools.codegen.languages.KotlinClientCodegen; -import io.swagger.models.*; -import io.swagger.models.properties.*; - -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -@SuppressWarnings("static-method") -public class KotlinClientCodegenModelTest { - - private Model getArrayTestModel() { - return new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("examples", new ArrayProperty().items(new StringProperty())) - .required("id"); - } - - private Model getSimpleModel() { - return new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); - } - - private Model getMapModel() { - return new ModelImpl() - .description("a sample model") - .property("mapping", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); - } - - private Model getComplexModel() { - return new ModelImpl() - .description("a sample model") - .property("child", new RefProperty("#/definitions/Child")); - } - - @Test(description = "convert a simple model") - public void simpleModelTest() { - final Model model = getSimpleModel(); - final DefaultCodegen codegen = new KotlinClientCodegen(); - - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 3); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "kotlin.Long"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); - Assert.assertEquals(property1.baseType, "kotlin.Long"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isPrimitiveType); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.datatype, "kotlin.String"); - Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "null"); - Assert.assertEquals(property2.baseType, "kotlin.String"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isPrimitiveType); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.datatype, "java.time.LocalDateTime"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, "null"); - Assert.assertEquals(property3.baseType, "java.time.LocalDateTime"); - Assert.assertFalse(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - } - - @Test(description = "convert a simple model: threetenbp") - public void selectDateLibraryAsThreetenbp() { - final Model model = getSimpleModel(); - final KotlinClientCodegen codegen = new KotlinClientCodegen(); - codegen.setDateLibrary(KotlinClientCodegen.DateLibrary.THREETENBP.value); - codegen.processOpts(); - - final CodegenModel cm = codegen.fromModel("sample", model); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.datatype, "org.threeten.bp.LocalDateTime"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, "null"); - Assert.assertEquals(property3.baseType, "org.threeten.bp.LocalDateTime"); - Assert.assertFalse(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - } - - @Test(description = "convert a simple model: date string") - public void selectDateLibraryAsString() { - final Model model = getSimpleModel(); - final KotlinClientCodegen codegen = new KotlinClientCodegen(); - codegen.setDateLibrary(KotlinClientCodegen.DateLibrary.STRING.value); - codegen.processOpts(); - - final CodegenModel cm = codegen.fromModel("sample", model); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.datatype, "kotlin.String"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, "null"); - Assert.assertEquals(property3.baseType, "kotlin.String"); - Assert.assertFalse(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - } - - @Test(description = "convert a simple model: date java8") - public void selectDateLibraryAsJava8() { - final Model model = getSimpleModel(); - final KotlinClientCodegen codegen = new KotlinClientCodegen(); - codegen.setDateLibrary(KotlinClientCodegen.DateLibrary.JAVA8.value); - codegen.processOpts(); - - final CodegenModel cm = codegen.fromModel("sample", model); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.datatype, "java.time.LocalDateTime"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, "null"); - Assert.assertEquals(property3.baseType, "java.time.LocalDateTime"); - Assert.assertFalse(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - } - - @Test(description = "convert a model with array property to default kotlin.Array") - public void arrayPropertyTest() { - final Model model = getArrayTestModel(); - - final DefaultCodegen codegen = new KotlinClientCodegen(); - final CodegenModel generated = codegen.fromModel("sample", model); - - Assert.assertEquals(generated.name, "sample"); - Assert.assertEquals(generated.classname, "Sample"); - Assert.assertEquals(generated.description, "a sample model"); - Assert.assertEquals(generated.vars.size(), 2); - - final CodegenProperty property = generated.vars.get(1); - Assert.assertEquals(property.baseName, "examples"); - Assert.assertEquals(property.getter, "getExamples"); - Assert.assertEquals(property.setter, "setExamples"); - Assert.assertEquals(property.datatype, "kotlin.Array"); - Assert.assertEquals(property.name, "examples"); - Assert.assertEquals(property.defaultValue, "null"); - Assert.assertEquals(property.baseType, "kotlin.Array"); - Assert.assertEquals(property.containerType, "array"); - Assert.assertFalse(property.required); - Assert.assertTrue(property.isContainer); - } - - @Test(description = "convert a model with a map property") - public void mapPropertyTest() { - final Model model = getMapModel(); - final DefaultCodegen codegen = new KotlinClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "mapping"); - Assert.assertEquals(property1.datatype, "kotlin.collections.Map"); - Assert.assertEquals(property1.name, "mapping"); - Assert.assertEquals(property1.baseType, "kotlin.collections.Map"); - Assert.assertEquals(property1.containerType, "map"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - Assert.assertTrue(property1.isPrimitiveType); - } - - @Test(description = "convert a model with complex property") - public void complexPropertyTest() { - final Model model = getComplexModel(); - final DefaultCodegen codegen = new KotlinClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "child"); - Assert.assertEquals(property1.datatype, "Child"); - Assert.assertEquals(property1.name, "child"); - Assert.assertEquals(property1.baseType, "Child"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isNotContainer); - } - - @DataProvider(name = "modelNames") - public static Object[][] modelNames() { - return new Object[][]{ - {"TestNs.TestClass", new ModelNameTest("TestNs.TestClass", "TestNsTestClass")}, - {"$", new ModelNameTest("$", "Dollar")}, - {"for", new ModelNameTest("`for`", "`for`")}, - {"One listOptions() throws IllegalAccessException, InstantiationException { - final String packageName = "org.openapitools.codegen.languages"; - final Reflections reflections = new Reflections(packageName); - final List codegenList = new ArrayList(); - - for (Class codegen : reflections.getSubTypesOf(DefaultCodegen.class)) { - if (!Modifier.isAbstract(codegen.getModifiers())) { - codegenList.add((new Object[] {codegen.newInstance()})); - } - } - if (codegenList.size() == 0) { - Assert.fail(String.format("No classes for testing have been found in the package %s", packageName)); - } - - return codegenList.iterator(); - } - - @Test(dataProvider = OPTIONS_PROVIDER) - public void booleanOptionsTest(DefaultCodegen codegen) { - for (CliOption option : codegen.cliOptions()) { - if (option.getType().equals(BooleanProperty.TYPE)) { - Assert.assertNotNull(option.getDefault()); - Assert.assertTrue(option.getDefault().equals(Boolean.TRUE.toString()) || - option.getDefault().equals(Boolean.FALSE.toString())); - } - } - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/ClojureClientCodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/ClojureClientCodegenTest.java deleted file mode 100644 index 795198847e40..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/ClojureClientCodegenTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.openapitools.codegen.languages; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class ClojureClientCodegenTest { - ClojureClientCodegen codegen = new ClojureClientCodegen(); - - @Test - public void testSanitizeTag() throws Exception { - Assert.assertEquals(codegen.sanitizeTag("users-api"), "users_api"); - Assert.assertEquals(codegen.sanitizeTag("users_api"), "users_api"); - Assert.assertEquals(codegen.sanitizeTag("users api"), "users_api"); - Assert.assertEquals(codegen.sanitizeTag("users.api"), "users_api"); - Assert.assertEquals(codegen.sanitizeTag("Users Api"), "Users_Api"); - Assert.assertEquals(codegen.sanitizeTag("UsersApi"), "UsersApi"); - Assert.assertEquals(codegen.sanitizeTag("usersapi"), "usersapi"); - Assert.assertEquals(codegen.sanitizeTag("Usersapi"), "Usersapi"); - } - - @Test - public void testToApiName() throws Exception { - Assert.assertEquals(codegen.toApiName("users_api"), "users-api"); - Assert.assertEquals(codegen.toApiName("Users_Api"), "users-api"); - Assert.assertEquals(codegen.toApiName("UsersApi"), "users-api"); - Assert.assertEquals(codegen.toApiName("usersapi"), "usersapi"); - Assert.assertEquals(codegen.toApiName("Usersapi"), "usersapi"); - } - - @Test - public void testToApiFilename() throws Exception { - Assert.assertEquals(codegen.toApiFilename("users_api"), "users_api"); - Assert.assertEquals(codegen.toApiFilename("Users_Api"), "users_api"); - Assert.assertEquals(codegen.toApiFilename("UsersApi"), "users_api"); - Assert.assertEquals(codegen.toApiFilename("usersapi"), "usersapi"); - Assert.assertEquals(codegen.toApiFilename("Usersapi"), "usersapi"); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/JavaClientCodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/JavaClientCodegenTest.java deleted file mode 100644 index 1dcebd9a5661..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/JavaClientCodegenTest.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.openapitools.codegen.languages; - -import static org.openapitools.codegen.languages.JavaClientCodegen.RETROFIT_2; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenParameter; - -public class JavaClientCodegenTest { - - private static final String VENDOR_MIME_TYPE = "application/vnd.company.v1+json"; - private static final String XML_MIME_TYPE = "application/xml"; - private static final String JSON_MIME_TYPE = "application/json"; - private static final String TEXT_MIME_TYPE = "text/plain"; - - @Test - public void testJsonMime() { - Assert.assertTrue(JavaClientCodegen.isJsonMimeType(JSON_MIME_TYPE)); - Assert.assertFalse(JavaClientCodegen.isJsonMimeType(XML_MIME_TYPE)); - Assert.assertFalse(JavaClientCodegen.isJsonMimeType(TEXT_MIME_TYPE)); - - Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany+json")); - Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.v1+json")); - Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.resourceTypeA.version1+json")); - Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.resourceTypeB.version2+json")); - Assert.assertFalse(JavaClientCodegen.isJsonVendorMimeType("application/v.json")); - - } - - @Test - public void testContentTypePrioritization() { - Map jsonMimeType = new HashMap<>(); - jsonMimeType.put(JavaClientCodegen.MEDIA_TYPE, JSON_MIME_TYPE); - - Map xmlMimeType = new HashMap<>(); - xmlMimeType.put(JavaClientCodegen.MEDIA_TYPE, XML_MIME_TYPE); - - Map vendorMimeType = new HashMap<>(); - vendorMimeType.put(JavaClientCodegen.MEDIA_TYPE, VENDOR_MIME_TYPE); - - Map textMimeType = new HashMap<>(); - textMimeType.put(JavaClientCodegen.MEDIA_TYPE, TEXT_MIME_TYPE); - - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes( - Collections.>emptyList()), Collections.emptyList()); - - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType)), Arrays.asList(xmlMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType)), Arrays.asList(jsonMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(vendorMimeType)), Arrays.asList(vendorMimeType)); - - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, jsonMimeType)), - Arrays.asList(jsonMimeType, xmlMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType, xmlMimeType)), - Arrays.asList(jsonMimeType, xmlMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType, vendorMimeType)), - Arrays.asList(vendorMimeType, jsonMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(textMimeType, xmlMimeType)), - Arrays.asList(textMimeType, xmlMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, textMimeType)), - Arrays.asList(xmlMimeType, textMimeType)); - - System.out.println(JavaClientCodegen.prioritizeContentTypes(Arrays.asList( - xmlMimeType,textMimeType, jsonMimeType, vendorMimeType))); - - List> priContentTypes = JavaClientCodegen.prioritizeContentTypes(Arrays.asList( - xmlMimeType, textMimeType, jsonMimeType, vendorMimeType)); - Assert.assertEquals(priContentTypes, Arrays.asList(vendorMimeType, jsonMimeType, xmlMimeType, textMimeType)); - - for ( int i = 0; i < 3; i++ ) - Assert.assertNotNull(priContentTypes.get(i).get("hasMore")); - - Assert.assertNull(priContentTypes.get(3).get("hasMore")); - } - - @Test - public void testParametersAreCorrectlyOrderedWhenUsingRetrofit(){ - JavaClientCodegen javaClientCodegen = new JavaClientCodegen(); - javaClientCodegen.setLibrary(RETROFIT_2); - - CodegenOperation codegenOperation = new CodegenOperation(); - CodegenParameter queryParamRequired = createQueryParam("queryParam1", true); - CodegenParameter queryParamOptional = createQueryParam("queryParam2", false); - CodegenParameter pathParam1 = createPathParam("pathParam1"); - CodegenParameter pathParam2 = createPathParam("pathParam2"); - - codegenOperation.allParams = Arrays.asList(queryParamRequired, pathParam1, pathParam2, queryParamOptional); - Map operations = ImmutableMap.of("operation", Arrays.asList(codegenOperation)); - - Map objs = ImmutableMap.of("operations", operations, "imports", new ArrayList>()); - - javaClientCodegen.postProcessOperations(objs); - - Assert.assertEquals(Arrays.asList(pathParam1, pathParam2, queryParamRequired, queryParamOptional), codegenOperation.allParams); - Assert.assertTrue(pathParam1.hasMore); - Assert.assertTrue(pathParam2.hasMore); - Assert.assertTrue(queryParamRequired.hasMore); - Assert.assertFalse(queryParamOptional.hasMore); - - } - - private CodegenParameter createPathParam(String name) { - CodegenParameter codegenParameter = createStringParam(name); - codegenParameter.isPathParam = true; - return codegenParameter; - } - - private CodegenParameter createQueryParam(String name, boolean required) { - CodegenParameter codegenParameter = createStringParam(name); - codegenParameter.isQueryParam = true; - codegenParameter.required = required; - return codegenParameter; - } - - private CodegenParameter createStringParam(String name){ - CodegenParameter codegenParameter = new CodegenParameter(); - codegenParameter.paramName = name; - codegenParameter.baseName = name; - codegenParameter.dataType = "String"; - return codegenParameter; - } - - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegenTest.java deleted file mode 100644 index 1bba4f4e3a2a..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegenTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.openapitools.codegen.languages; - -import org.openapitools.codegen.CliOption; -import org.openapitools.codegen.SupportingFile; -import io.swagger.models.properties.BooleanProperty; -import org.junit.Test; -import org.testng.Assert; - -public class JavaJAXRSSpecServerCodegenTest { - - private JavaJAXRSSpecServerCodegen generator = new JavaJAXRSSpecServerCodegen(); - - @Test - public void do_not_process_RestApplication_when_interfaceOnly_is_true() { - generator.additionalProperties().put(JavaJAXRSSpecServerCodegen.INTERFACE_ONLY, "true"); - generator.processOpts(); - for (SupportingFile file : generator.supportingFiles()) { - Assert.assertNotEquals("RestApplication.mustache", file.templateFile); - } - } - - @Test - public void do_process_pom_by_default() { - generator.processOpts(); - for (SupportingFile file : generator.supportingFiles()) { - if ("pom.mustache".equals(file.templateFile)) { - return; - } - } - Assert.fail("Missing pom.mustache"); - } - - @Test - public void process_pom_if_generatePom_is_true() { - generator.additionalProperties().put(JavaJAXRSSpecServerCodegen.GENERATE_POM, "true"); - generator.processOpts(); - for (SupportingFile file : generator.supportingFiles()) { - if ("pom.mustache".equals(file.templateFile)) { - return; - } - } - Assert.fail("Missing pom.mustache"); - } - - @Test - public void do_not_process_pom_if_generatePom_is_false() { - generator.additionalProperties().put(JavaJAXRSSpecServerCodegen.GENERATE_POM, "false"); - generator.processOpts(); - for (SupportingFile file : generator.supportingFiles()) { - Assert.assertNotEquals("pom.mustache", file.templateFile); - } - } - - @Test - public void verify_that_generatePom_exists_as_a_parameter_with_default_true() { - for (CliOption option : generator.cliOptions()) { - if (option.getOpt().equals(JavaJAXRSSpecServerCodegen.GENERATE_POM)) { - Assert.assertEquals(BooleanProperty.TYPE, option.getType()); - Assert.assertEquals("true", option.getDefault()); - return; - } - } - Assert.fail("Missing " + JavaJAXRSSpecServerCodegen.GENERATE_POM); - } - - @Test - public void verify_that_returnResponse_is_removed_from_additional_properties_if_false() { - generator.additionalProperties().put(JavaJAXRSSpecServerCodegen.RETURN_RESPONSE, Boolean.FALSE.toString()); - generator.processOpts(); - Assert.assertFalse(generator.additionalProperties().containsKey(JavaJAXRSSpecServerCodegen.RETURN_RESPONSE)); - } - - @Test - public void verify_that_returnResponse_is_preserved_in_additional_properties_if_true() { - generator.additionalProperties().put(JavaJAXRSSpecServerCodegen.RETURN_RESPONSE, Boolean.TRUE.toString()); - generator.processOpts(); - Assert.assertTrue(generator.additionalProperties().containsKey(JavaJAXRSSpecServerCodegen.RETURN_RESPONSE)); - } - - @Test - public void verify_that_interfaceOnly_exists_as_a_parameter_with_default_false() { - for (CliOption option : generator.cliOptions()) { - if (option.getOpt().equals(JavaJAXRSSpecServerCodegen.INTERFACE_ONLY)) { - Assert.assertEquals(BooleanProperty.TYPE, option.getType()); - Assert.assertEquals("false", option.getDefault()); - return; - } - } - Assert.fail("Missing " + JavaJAXRSSpecServerCodegen.INTERFACE_ONLY); - } - - @Test - public void verify_that_interfaceOnly_is_removed_from_additional_properties_if_false() { - generator.additionalProperties().put(JavaJAXRSSpecServerCodegen.INTERFACE_ONLY, Boolean.FALSE.toString()); - generator.processOpts(); - Assert.assertFalse(generator.additionalProperties().containsKey(JavaJAXRSSpecServerCodegen.INTERFACE_ONLY)); - } - - @Test - public void verify_that_interfaceOnly_is_preserved_in_additional_properties_if_true() { - generator.additionalProperties().put(JavaJAXRSSpecServerCodegen.INTERFACE_ONLY, Boolean.TRUE.toString()); - generator.processOpts(); - Assert.assertTrue(generator.additionalProperties().containsKey(JavaJAXRSSpecServerCodegen.INTERFACE_ONLY)); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/RustServerCodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/RustServerCodegenTest.java deleted file mode 100644 index 02cf4c7a1a43..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/RustServerCodegenTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.openapitools.codegen.languages; - -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; - -public class RustServerCodegenTest { - - @Test - public void testRustIntSize() { - assertEquals(RustServerCodegen.matchingIntType(true, null, null), "usize"); - assertEquals(RustServerCodegen.matchingIntType(true, 0L, null), "usize"); - assertEquals(RustServerCodegen.matchingIntType(true, 0xFFL, null), "usize"); - assertEquals(RustServerCodegen.matchingIntType(true, 0xFFFFL, null), "usize"); - assertEquals(RustServerCodegen.matchingIntType(true, 0x10000L, null), "u32"); - assertEquals(RustServerCodegen.matchingIntType(true, 0xFFFFFFFFL, null), "u32"); - assertEquals(RustServerCodegen.matchingIntType(true, 0x100000000L, null), "u64"); - assertEquals(RustServerCodegen.matchingIntType(true, null, 0xFFL), "u8"); - assertEquals(RustServerCodegen.matchingIntType(true, null, 0x100L), "u16"); - assertEquals(RustServerCodegen.matchingIntType(true, null, 0xFFFFL), "u16"); - assertEquals(RustServerCodegen.matchingIntType(true, null, 0x10000L), "u32"); - assertEquals(RustServerCodegen.matchingIntType(true, null, 0xFFFFFFFFL), "u32"); - assertEquals(RustServerCodegen.matchingIntType(true, null, 0x100000000L), "u64"); - assertEquals(RustServerCodegen.matchingIntType(true, 0xFFL, 0xFFL), "u8"); - assertEquals(RustServerCodegen.matchingIntType(true, 0x100L, 0x100L), "u16"); - assertEquals(RustServerCodegen.matchingIntType(true, 0xFFFFL, 0xFFFFL), "u16"); - assertEquals(RustServerCodegen.matchingIntType(true, 0x10000L, 0x10000L), "u32"); - assertEquals(RustServerCodegen.matchingIntType(true, 0xFFFFFFFFL, 0xFFFFFFFFL), "u32"); - assertEquals(RustServerCodegen.matchingIntType(true, 0x100000000L, 0x100000000L), "u64"); - - assertEquals(RustServerCodegen.matchingIntType(false, null, null), "isize"); - assertEquals(RustServerCodegen.matchingIntType(false, -256L, null), "isize"); - assertEquals(RustServerCodegen.matchingIntType(false, -257L, null), "isize"); - assertEquals(RustServerCodegen.matchingIntType(false, -16385L, null), "isize"); - assertEquals(RustServerCodegen.matchingIntType(false, ((long) Short.MIN_VALUE) - 1, null), "i32"); - assertEquals(RustServerCodegen.matchingIntType(false, (long) Integer.MIN_VALUE, null), "i32"); - assertEquals(RustServerCodegen.matchingIntType(false, ((long) Integer.MIN_VALUE) - 1, null), "i64"); - assertEquals(RustServerCodegen.matchingIntType(false, Long.MIN_VALUE, null), "i64"); - assertEquals(RustServerCodegen.matchingIntType(false, null, 127L), "i8"); - assertEquals(RustServerCodegen.matchingIntType(false, null, 128L), "i16"); - assertEquals(RustServerCodegen.matchingIntType(false, null, (long) Short.MAX_VALUE), "i16"); - assertEquals(RustServerCodegen.matchingIntType(false, null, (long) Short.MAX_VALUE + 1), "i32"); - assertEquals(RustServerCodegen.matchingIntType(false, null, (long) Integer.MAX_VALUE), "i32"); - assertEquals(RustServerCodegen.matchingIntType(false, null, (long) Integer.MAX_VALUE + 1), "i64"); - assertEquals(RustServerCodegen.matchingIntType(false, null, Long.MAX_VALUE), "i64"); - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/ScalaCodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/ScalaCodegenTest.java deleted file mode 100644 index c3858095147d..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/languages/ScalaCodegenTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.openapitools.codegen.languages; - -import org.openapitools.codegen.CodegenProperty; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class ScalaCodegenTest { - - private ScalaClientCodegen scalaClientCodegen; - - @BeforeTest - public void setup() { - this.scalaClientCodegen = new ScalaClientCodegen(); - } - - @Test - public void shouldCallFormatIdentifierOnGetModelName() { - String className = "models.WebsiteBodyModel"; - - ScalaClientCodegen scalaClientCodegenSpy = Mockito.spy(this.scalaClientCodegen); - - String result = scalaClientCodegenSpy.toModelName(className); - - verify(scalaClientCodegenSpy, times(1)).stripPackageName(anyString()); - Assert.assertEquals("WebsiteBodyModel", result); - } - - @Test - public void shouldCallFormatIdentifierOnToEnumName() { - String className = "models.WebsiteBodyModel"; - ScalaClientCodegen scalaClientCodegenSpy = Mockito.spy(this.scalaClientCodegen); - CodegenProperty property = new CodegenProperty(); - property.baseName = className; - String result = scalaClientCodegenSpy.toEnumName(property); - verify(scalaClientCodegenSpy, times(1)).stripPackageName(anyString()); - verify(scalaClientCodegenSpy, times(1)).formatIdentifier(anyString(), anyBoolean()); - Assert.assertEquals("WebsiteBodyModel", result); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java deleted file mode 100644 index 9a2708372511..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.openapitools.codegen.lumen; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.LumenServerCodegen; -import org.openapitools.codegen.options.LumenServerOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class LumenServerOptionsTest extends AbstractOptionsTest { - - @Tested - private LumenServerCodegen clientCodegen; - - public LumenServerOptionsTest() { - super(new LumenServerOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(LumenServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setParameterNamingConvention(LumenServerOptionsProvider.VARIABLE_NAMING_CONVENTION_VALUE); - clientCodegen.setModelPackage(LumenServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(LumenServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - times = 1; - clientCodegen.setInvokerPackage(LumenServerOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setPackagePath(LumenServerOptionsProvider.PACKAGE_PATH_VALUE); - times = 1; - clientCodegen.setSrcBasePath(LumenServerOptionsProvider.SRC_BASE_PATH_VALUE); - times = 1; - clientCodegen.setGitUserId(LumenServerOptionsProvider.GIT_USER_ID_VALUE); - times = 1; - clientCodegen.setGitRepoId(LumenServerOptionsProvider.GIT_REPO_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(LumenServerOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/CamelCaseLambdaTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/CamelCaseLambdaTest.java deleted file mode 100644 index 42304b0d6ca1..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/CamelCaseLambdaTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.openapitools.codegen.mustache; - -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.CSharpClientCodegen; -import org.openapitools.codegen.languages.ScalaClientCodegen; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import static org.testng.Assert.*; - -public class CamelCaseLambdaTest extends MustacheTestBase { - private final String input; - private final String expected; - private Boolean escapeAsParamName = false; - - private CodegenConfig generator = null; - - public CamelCaseLambdaTest(String input, String expected) { - this.input = input; - this.expected = expected; - } - - public CamelCaseLambdaTest generator(CodegenConfig generator) { - this.generator = generator; - return this; - } - - public CamelCaseLambdaTest escapeAsParamName(Boolean setting) { - this.escapeAsParamName = setting; - return this; - } - - @Test(description = "camelCase expected inputs") - public void testExecute() throws Exception { - // Arrange - String template = "{{#camelcase}}{{value}}{{/camelcase}}"; - Object inputCtx = context( - "camelcase", new CamelCaseLambda().generator(this.generator).escapeAsParamName(this.escapeAsParamName), - "value", this.input - ); - - // Act - String actual = compile(template, inputCtx); - - - // Assert - assertEquals(actual, this.expected); - } - - @Factory - public static Object[] factoryMethod() { - return new Object[] { - new CamelCaseLambdaTest("lowercase input", "lowercase input"), - - // NOTE: DefaultCodegen.camelize(string, true) only results in first character of first word being lowercased. - // Keeping this behavior as it will match whatever is expected by existing codegen implementations. - new CamelCaseLambdaTest("UPPERCASE INPUT", "uPPERCASE INPUT"), - new CamelCaseLambdaTest("inputText", "inputText"), - new CamelCaseLambdaTest("input_text", "inputText"), - - // TODO: This result for INPUT_TEXT may be unexpected, but is the result of DefaultCodegen.camelize. - // CamelCaseLambda can be extended to accept a method reference after move to Java 8. - new CamelCaseLambdaTest("INPUT_TEXT", "iNPUTTEXT"), - new CamelCaseLambdaTest("input-text", "inputText"), - new CamelCaseLambdaTest("input-text input-text input-text input-text input-text", "inputText inputText inputText inputText inputText"), - // C# codegen at time of writing this test escapes using a character that would be removed by camelize function. - new CamelCaseLambdaTest("class", "_class").generator(new CSharpClientCodegen()), - new CamelCaseLambdaTest("123List", "_123List").generator(new CSharpClientCodegen()).escapeAsParamName(true), - // Scala codegen is only one at time of writing this test that uses a Mustache.Escaper - new CamelCaseLambdaTest("class", "`class`").generator(new ScalaClientCodegen()) - }; - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/IndentedLambdaTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/IndentedLambdaTest.java deleted file mode 100644 index 2f15cca9016e..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/IndentedLambdaTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.openapitools.codegen.mustache; - -import org.apache.commons.lang3.StringUtils; -import org.testng.annotations.Test; - -import java.util.Arrays; - -import static org.testng.Assert.assertEquals; - -public class IndentedLambdaTest extends MustacheTestBase { - - @Test(description = "indents by 4 spaces by default") - public void testFourSpaceIndent() throws Exception { - // Arrange - String indent = StringUtils.repeat(" ", 4); - String template = " {{#indent_4}}{{value}}{{/indent_4}}"; - String input = StringUtils.join( - Arrays.asList( - "line1", - "line2", - "", - "line3" - ), System.lineSeparator()); - String expected = StringUtils.join( - Arrays.asList( - indent + "line1", - indent + "line2", - indent + "", - indent + "line3" - ), System.lineSeparator()); - Object ctx = context( - "indent_4", new IndentedLambda(), - "value", input - ); - - // Act - String actual = compile(template, ctx); - - // Assert - assertEquals(actual, expected); - } - - @Test - public void testCustomCountAndDelim() throws Exception { - // Arrange - int count = 12; - String delim = "."; - String indent = StringUtils.repeat(delim, count); - String template = indent + "{{#indent_"+count+"}}{{value}}{{/indent_"+count+"}}"; - String input = StringUtils.join( - Arrays.asList( - "line1", - "line2", - "", - "line3" - ), System.lineSeparator()); - String expected = StringUtils.join( - Arrays.asList( - indent + "line1", - indent + "line2", - indent + "", - indent + "line3" - ), System.lineSeparator()); - Object ctx = context( - "indent_" + count, new IndentedLambda(count, delim), - "value", input - ); - - // Act - String actual = compile(template, ctx); - - // Assert - assertEquals(actual, expected); - } - - @Test(description = "throws illegal arg for count < 0.", - expectedExceptions = { IllegalArgumentException.class }, - expectedExceptionsMessageRegExp = "prefixSpaceCount must be greater than 0" - ) - public void testRequiresValidCount() throws Exception { - // Arrange - int count = -1; - - // Act - IndentedLambda instance = new IndentedLambda(count, " "); - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/LowercaseLambdaTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/LowercaseLambdaTest.java deleted file mode 100644 index 47e1b9210111..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/LowercaseLambdaTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.openapitools.codegen.mustache; - -import org.openapitools.codegen.languages.CSharpClientCodegen; -import org.testng.annotations.Test; - -import static org.testng.Assert.*; - -public class LowercaseLambdaTest extends MustacheTestBase { - - @Test(description = "lowercases expected inputs") - public void testExecute() throws Exception { - // Arrange - String template = "{{#lowercase}}{{value}}{{/lowercase}}"; - Object lowercaseCtx = context( - "lowercase", new LowercaseLambda(), - "value", "lowercase input" - ); - Object uppercaseCtx = context( - "lowercase", new LowercaseLambda(), - "value", "UPPERCASE INPUT" - ); - - // Act - String lowercaseResult = compile(template, lowercaseCtx); - String uppercaseResult = compile(template, uppercaseCtx); - - - // Assert - assertEquals(lowercaseResult, "lowercase input"); - assertEquals(uppercaseResult, "uppercase input"); - } - - @Test(description = "lowercase escapes reserved words") - public void testEscapingReservedWords() { - // Arrange - String template = "{{#lowercase}}{{value}}{{/lowercase}}"; - String expected = "_class"; - Object ctx = context( - "lowercase", new LowercaseLambda().generator(new CSharpClientCodegen()), - "value", "CLASS" - ); - - // Act - String actual = compile(template, ctx); - - // Assert - assertEquals(actual, expected); - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/MustacheTestBase.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/MustacheTestBase.java deleted file mode 100644 index 07e47c12bcad..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/MustacheTestBase.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.openapitools.codegen.mustache; - -import com.samskivert.mustache.Mustache; - -import java.util.HashMap; -import java.util.Map; - -public abstract class MustacheTestBase { - protected Object context(Object... data) { - Map ctx = new HashMap<>(); - if (data.length % 2 != 0) { - throw new IllegalArgumentException("context helper accepts pairs of key/value varargs"); - } - for (int i = 0; i < data.length; i += 2) { - ctx.put(data[i].toString(), data[i + 1]); - } - return ctx; - } - protected String compile(String template, Object context) { - return Mustache.compiler().compile(template).execute(context); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/TitlecaseLambdaTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/TitlecaseLambdaTest.java deleted file mode 100644 index 35c9e292e07c..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/TitlecaseLambdaTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.openapitools.codegen.mustache; - -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; - -public class TitlecaseLambdaTest extends MustacheTestBase { - - private String template = "{{#titlecase}}{{value}}{{/titlecase}}"; - - @Test(description = "title cases single word") - public void testTitlecase() throws Exception { - // Arrange - String input = "single"; - String expected = "Single"; - Object ctx = context( - "titlecase", new TitlecaseLambda(), - "value", input - ); - - // Act - String actual = compile(template, ctx); - - // Assert - assertEquals(actual, expected); - } - - @Test(description = "title cases multiple words based on custom delimeter") - public void testTitlecaseCustomDelim() throws Exception { - // Arrange - String input = "one|or|more|words"; - String expected = "One|Or|More|Words"; - Object ctx = context( - "titlecase", new TitlecaseLambda("|"), - "value", input - ); - - // Act - String actual = compile(template, ctx); - - // Assert - assertEquals(actual, expected); - } - - @Test(description = "title cases first word when delim is null") - public void testTitlecaseFirstWord() throws Exception { - // Arrange - String input = "one or more words"; - String expected = "One or more words"; - Object ctx = context( - "titlecase", new TitlecaseLambda(null), - "value", input - ); - - // Act - String actual = compile(template, ctx); - - // Assert - assertEquals(actual, expected); - } - - @Test(description = "title cases multiple words") - public void testTitlecaseMultipleWords() throws Exception { - // Arrange - String input = "one or more words"; - String expected = "One Or More Words"; - Object ctx = context( - "titlecase", new TitlecaseLambda(), - "value", input - ); - - // Act - String actual = compile(template, ctx); - - // Assert - assertEquals(actual, expected); - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/UppercaseLambdaTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/UppercaseLambdaTest.java deleted file mode 100644 index 7d9683906d8d..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/mustache/UppercaseLambdaTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.openapitools.codegen.mustache; - -import com.samskivert.mustache.Mustache; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.testng.Assert.*; - -public class UppercaseLambdaTest extends MustacheTestBase { - - @Test(description = "uppercases expected inputs") - public void testExecute() throws Exception { - // Arrange - String template = "{{#uppercase}}{{value}}{{/uppercase}}"; - Object lowercaseCtx = context( - "uppercase", new UppercaseLambda(), - "value", "lowercase input" - ); - Object uppercaseCtx = context( - "uppercase", new UppercaseLambda(), - "value", "UPPERCASE INPUT" - ); - - // Act - String lowercaseResult = compile(template, lowercaseCtx); - String uppercaseResult = compile(template, uppercaseCtx); - - - // Assert - assertEquals(lowercaseResult, "LOWERCASE INPUT"); - assertEquals(uppercaseResult, "UPPERCASE INPUT"); - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java deleted file mode 100644 index 9f0f7f8dfbdc..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.openapitools.codegen.nodejs; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.NodeJSServerCodegen; -import org.openapitools.codegen.options.NodeJSServerOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; - -public class NodeJSServerOptionsTest extends AbstractOptionsTest { - - @Tested - private NodeJSServerCodegen clientCodegen; - - public NodeJSServerOptionsTest() { - super(new NodeJSServerOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(NodeJSServerOptionsProvider.SORT_PARAMS_VALUE)); - clientCodegen.setGoogleCloudFunctions(Boolean.valueOf(NodeJSServerOptionsProvider.GOOGLE_CLOUD_FUNCTIONS)); - clientCodegen.setExportedName(NodeJSServerOptionsProvider.EXPORTED_NAME); - times = 1; - }}; - } - - - @Test - public void testCleanTitle() { - String dirtyTitle = "safe-title"; - String clean = dirtyTitle.replaceAll("[^a-zA-Z0-9]", "-") - .replaceAll("^[-]*", "") - .replaceAll("[-]*$", "") - .replaceAll("[-]{2,}", "-"); - - assertEquals(clean, "safe-title"); - } - - @Test - public void testDirtyTitleCleansing() { - String dirtyTitle = "_it's-$ooo//////////---_//dirty!!!!"; - String clean = dirtyTitle.replaceAll("[^a-zA-Z0-9]", "-") - .replaceAll("^[-]*", "") - .replaceAll("[-]*$", "") - .replaceAll("[-]{2,}", "-"); - - assertEquals(clean, "it-s-ooo-dirty"); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java deleted file mode 100644 index 3d5fb8723bd2..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import com.sun.org.apache.bcel.internal.classfile.Code; - -import java.util.Map; - -public class AkkaScalaClientOptionsProvider implements OptionsProvider { - public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; - public static final String MODEL_PACKAGE_VALUE = "package"; - public static final String API_PACKAGE_VALUE = "apiPackage"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - @Override - public String getLanguage() { - return "akka-scala"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java deleted file mode 100644 index 6b082417b183..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.AndroidClientCodegen; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class AndroidClientOptionsProvider implements OptionsProvider { - public static final String ARTIFACT_ID_VALUE = "swagger-java-client-test"; - public static final String MODEL_PACKAGE_VALUE = "package"; - public static final String API_PACKAGE_VALUE = "apiPackage"; - public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String GROUP_ID_VALUE = "io.swagger.test"; - public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; - public static final String ANDROID_MAVEN_GRADLE_PLUGIN_VALUE = "true"; - public static final String ANDROID_GRADLE_VERSION_VALUE = "2.3.0"; - public static final String ANDROID_SDK_VERSION_VALUE = "26"; - public static final String ANDROID_BUILD_TOOLS_VERSION_VALUE = "26.0.0"; - public static final String LIBRARY_VALUE = "httpclient"; - public static final String SERIALIZABLE_MODEL_VALUE = "false"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - @Override - public String getLanguage() { - return "android"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) - .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) - .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(AndroidClientCodegen.USE_ANDROID_MAVEN_GRADLE_PLUGIN, ANDROID_MAVEN_GRADLE_PLUGIN_VALUE) - .put(AndroidClientCodegen.ANDROID_GRADLE_VERSION, ANDROID_GRADLE_VERSION_VALUE) - .put(AndroidClientCodegen.ANDROID_SDK_VERSION, ANDROID_SDK_VERSION_VALUE) - .put(AndroidClientCodegen.ANDROID_BUILD_TOOLS_VERSION, ANDROID_BUILD_TOOLS_VERSION_VALUE) - .put(CodegenConstants.LIBRARY, LIBRARY_VALUE) - .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AspNetCoreServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AspNetCoreServerOptionsProvider.java deleted file mode 100644 index 7310c57ad23c..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AspNetCoreServerOptionsProvider.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openapitools.codegen.options; - -import com.google.common.collect.ImmutableMap; -import org.openapitools.codegen.CodegenConstants; - -import java.util.Map; - -public class AspNetCoreServerOptionsProvider implements OptionsProvider { - public static final String PROJECT_GUID_VALUE = "{0FBE6C2F-40D5-4F36-85B0-365EBF0D7EE3}"; - public static final String PACKAGE_NAME_VALUE = "swagger_server_aspnetcore"; - public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String SOURCE_FOLDER_VALUE = "src_aspnetcore"; - - @Override - public String getLanguage() { - return "aspnetcore"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) - .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.OPTIONAL_PROJECT_GUID, PROJECT_GUID_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") - .put(CodegenConstants.USE_DATETIME_OFFSET, "true") - .put(CodegenConstants.USE_COLLECTION, "false") - .put(CodegenConstants.RETURN_ICOLLECTION, "false") - .build(); - } - - @Override - public boolean isServer() { - return true; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java deleted file mode 100644 index bf8db8bbfc2a..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class AsyncScalaClientOptionsProvider implements OptionsProvider { - public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; - public static final String MODEL_PACKAGE_VALUE = "package"; - public static final String API_PACKAGE_VALUE = "apiPackage"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - @Override - public String getLanguage() { - return "async-scala"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java deleted file mode 100644 index 9cd2d3f80add..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class CSharpClientOptionsProvider implements OptionsProvider { - public static final String PACKAGE_NAME_VALUE = "swagger_client_csharp"; - public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String SOURCE_FOLDER_VALUE = "src_csharp"; - public static final String PACKAGE_GUID_VALUE = "{894EAEBB-649A-498C-A735-10D0BD7B73E0}"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming"; - - @Override - public String getLanguage() { - return "csharp"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) - .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") - .put(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, "true") - .put(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, "true") - .put(CodegenConstants.USE_DATETIME_OFFSET, "true") - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.USE_COLLECTION, "false") - .put(CodegenConstants.RETURN_ICOLLECTION, "false") - .put(CodegenConstants.OPTIONAL_PROJECT_FILE, "true") - .put(CodegenConstants.OPTIONAL_PROJECT_GUID, PACKAGE_GUID_VALUE) - .put(CodegenConstants.DOTNET_FRAMEWORK, "4.x") - .put(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, "true") - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .put(CodegenConstants.GENERATE_PROPERTY_CHANGED, "true") - .put(CodegenConstants.NON_PUBLIC_API, "true") - .put(CodegenConstants.INTERFACE_PREFIX, "X") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .put(CodegenConstants.NETCORE_PROJECT_FILE, "false") - .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING) - .put(CodegenConstants.VALIDATABLE, "true") - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/CsharpDotNet2ClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/CsharpDotNet2ClientOptionsProvider.java deleted file mode 100644 index b213c8c08cc2..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/CsharpDotNet2ClientOptionsProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.CsharpDotNet2ClientCodegen; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class CsharpDotNet2ClientOptionsProvider implements OptionsProvider { - public static final String PACKAGE_NAME_VALUE = "swagger_client_csharp_dotnet"; - public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String CLIENT_PACKAGE_VALUE = "IO.Swagger.Client.Test"; - - @Override - public String getLanguage() { - return "CsharpDotNet2"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) - .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) - .put(CsharpDotNet2ClientCodegen.CLIENT_PACKAGE, CLIENT_PACKAGE_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/EiffelClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/EiffelClientOptionsProvider.java deleted file mode 100644 index b832705634c2..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/EiffelClientOptionsProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.openapitools.codegen.options; - -import java.util.Map; - -import com.google.common.collect.ImmutableMap; - -import org.openapitools.codegen.CodegenConstants; - -public class EiffelClientOptionsProvider implements OptionsProvider { - - public static final String PACKAGE_VERSION_VALUE = "1.0.0"; - public static final String PACKAGE_NAME_VALUE = "Eiffel"; - - @Override - public String getLanguage() { - return "eiffel"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder - .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) - .put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .build(); - } - - @Override - public boolean isServer() { - return false; - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/FlashClienOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/FlashClienOptionsProvider.java deleted file mode 100644 index 3021eee91727..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/FlashClienOptionsProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class FlashClienOptionsProvider implements OptionsProvider { - public static final String PACKAGE_NAME_VALUE = "io.swagger.flash"; - public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String INVOKER_PACKAGE_VALUE = "io.swagger.flash"; - public static final String SOURCE_FOLDER_VALUE = "src/main/flex/test"; - - @Override - public String getLanguage() { - return "flash"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) - .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) - .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/HaskellHttpClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/HaskellHttpClientOptionsProvider.java deleted file mode 100644 index 489ea7a4a6b9..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/HaskellHttpClientOptionsProvider.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.openapitools.codegen.options; - -import com.google.common.collect.ImmutableMap; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.HaskellHttpClientCodegen; - -import java.util.Map; - -public class HaskellHttpClientOptionsProvider implements OptionsProvider { - public static final String MODEL_PACKAGE_VALUE = "Model"; - public static final String API_PACKAGE_VALUE = "Api"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - public static final String HIDE_GENERATION_TIMESTAMP = "true"; - - public static final String ALLOW_NONUNIQUE_OPERATION_IDS = "false"; - public static final String ALLOW_FROMJSON_NULLS = "true"; - public static final String ALLOW_TOJSON_NULLS = "false"; - public static final String DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S%Q%z"; - public static final String DATE_FORMAT = "%Y-%m-%d"; - public static final String MODEL_DERIVING = ""; - public static final String STRICT_FIELDS = "false"; - public static final String GENERATE_ENUMS = "true"; - public static final String GENERATE_FORM_URLENCODED_INSTANCES = "true"; - public static final String GENERATE_LENSES = "true"; - public static final String GENERATE_MODEL_CONSTRUCTORS = "true"; - public static final String INLINE_MIME_TYPES = "false"; - public static final String USE_MONAD_LOGGER = "false"; - - public static final String CABAL_PACKAGE = "cabal-package"; - public static final String CABAL_VERSION = "1.0.0.0"; - public static final String BASE_MODULE = "Network.Module"; - public static final String REQUEST_TYPE = "RequestType"; - public static final String CONFIG_TYPE = "ConfigType"; - - @Override - public String getLanguage() { - return "haskell-http-client"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, HIDE_GENERATION_TIMESTAMP) - - .put(HaskellHttpClientCodegen.PROP_ALLOW_NONUNIQUE_OPERATION_IDS, ALLOW_NONUNIQUE_OPERATION_IDS) - .put(HaskellHttpClientCodegen.PROP_ALLOW_FROMJSON_NULLS, ALLOW_FROMJSON_NULLS) - .put(HaskellHttpClientCodegen.PROP_ALLOW_TOJSON_NULLS, ALLOW_TOJSON_NULLS) - .put(HaskellHttpClientCodegen.PROP_DATETIME_FORMAT, DATETIME_FORMAT) - .put(HaskellHttpClientCodegen.PROP_DATE_FORMAT, DATE_FORMAT) - .put(HaskellHttpClientCodegen.PROP_MODEL_DERIVING, MODEL_DERIVING) - .put(HaskellHttpClientCodegen.PROP_GENERATE_ENUMS, GENERATE_ENUMS) - .put(HaskellHttpClientCodegen.PROP_GENERATE_FORM_URLENCODED_INSTANCES, GENERATE_FORM_URLENCODED_INSTANCES) - .put(HaskellHttpClientCodegen.PROP_GENERATE_LENSES, GENERATE_LENSES) - .put(HaskellHttpClientCodegen.PROP_GENERATE_MODEL_CONSTRUCTORS, GENERATE_MODEL_CONSTRUCTORS) - .put(HaskellHttpClientCodegen.PROP_INLINE_MIME_TYPES, INLINE_MIME_TYPES) - .put(HaskellHttpClientCodegen.PROP_STRICT_FIELDS, STRICT_FIELDS) - .put(HaskellHttpClientCodegen.PROP_USE_MONAD_LOGGER, USE_MONAD_LOGGER) - .put(HaskellHttpClientCodegen.PROP_CABAL_PACKAGE, CABAL_PACKAGE) - .put(HaskellHttpClientCodegen.PROP_CABAL_VERSION, CABAL_VERSION) - .put(HaskellHttpClientCodegen.PROP_BASE_MODULE, BASE_MODULE) - .put(HaskellHttpClientCodegen.PROP_REQUEST_TYPE, REQUEST_TYPE) - .put(HaskellHttpClientCodegen.PROP_CONFIG_TYPE, CONFIG_TYPE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaCXFClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaCXFClientOptionsProvider.java deleted file mode 100644 index a1b9baf5591c..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaCXFClientOptionsProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.openapitools.codegen.options; - -import java.util.Map; - -import com.google.common.collect.ImmutableMap; - -import org.openapitools.codegen.languages.JavaCXFClientCodegen; - -public class JavaCXFClientOptionsProvider extends JavaOptionsProvider { - - public static final String USE_BEANVALIDATION = "true"; - - public static final String USE_GZIP_FEATURE_FOR_TESTS = "true"; - - public static final String USE_LOGGING_FEATURE_FOR_TESTS = "true"; - - public static final String USE_GENERIC_RESPONSE = "true"; - - - @Override - public boolean isServer() { - return false; - } - - @Override - public String getLanguage() { - return "jaxrs-cxf-client"; - } - - @Override - public Map createOptions() { - - Map parentOptions = super.createOptions(); - - ImmutableMap.Builder builder = new ImmutableMap.Builder() - .putAll(parentOptions); - - builder.put(JavaCXFClientCodegen.USE_BEANVALIDATION, JavaCXFClientOptionsProvider.USE_BEANVALIDATION); - builder.put(JavaCXFClientCodegen.USE_GENERIC_RESPONSE, JavaCXFClientOptionsProvider.USE_GENERIC_RESPONSE); - - builder.put(JavaCXFClientCodegen.USE_GZIP_FEATURE_FOR_TESTS, USE_GZIP_FEATURE_FOR_TESTS); - builder.put(JavaCXFClientCodegen.USE_LOGGING_FEATURE_FOR_TESTS, USE_LOGGING_FEATURE_FOR_TESTS); - - return builder.build(); - - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaCXFServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaCXFServerOptionsProvider.java deleted file mode 100644 index eb8704c3c3ea..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaCXFServerOptionsProvider.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.openapitools.codegen.options; - -import java.util.Map; - -import com.google.common.collect.ImmutableMap; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.JavaCXFServerCodegen; - -public class JavaCXFServerOptionsProvider extends JavaOptionsProvider { - - public static final String GENERATE_SPRING_APPLICATION = "true"; - - public static final String USE_SWAGGER_FEATURE = "true"; - - public static final String USE_SWAGGER_UI = "true"; - - public static final String USE_WADL_FEATURE = "true"; - - public static final String USE_MULTIPART_FEATURE = "true"; - - public static final String USE_GZIP_FEATURE = "true"; - - public static final String USE_GZIP_FEATURE_FOR_TESTS = "true"; - - public static final String USE_LOGGING_FEATURE = "true"; - - public static final String USE_LOGGING_FEATURE_FOR_TESTS = "true"; - - public static final String USE_BEANVALIDATION_FEATURE = "true"; - - public static final String USE_GENERIC_RESPONSE = "true"; - - public static final String USE_SPRING_ANNOTATION_CONFIG = "true"; - - public static final String GENERATE_SPRING_BOOT_APPLICATION = "true"; - - public static final String GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR = "true"; - - public static final String ADD_CONSUMES_PRODUCES_JSON = "true"; - - public static final String IMPL_FOLDER_VALUE = "src/main/java"; - - public static final String USE_ANNOTATED_BASE_PATH = "true"; - - public static final String GENERATE_NON_SPRING_APPLICATION = "true"; - - @Override - public boolean isServer() { - return true; - } - - @Override - public String getLanguage() { - return "jaxrs-cxf"; - } - - @Override - public Map createOptions() { - - Map parentOptions = super.createOptions(); - - ImmutableMap.Builder builder = new ImmutableMap.Builder() - .putAll(parentOptions); - - builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE); - builder.put("title", "Test title"); - - builder.put(JavaCXFServerCodegen.USE_BEANVALIDATION, JavaOptionsProvider.USE_BEANVALIDATION); - - builder.put(JavaCXFServerCodegen.GENERATE_SPRING_APPLICATION, GENERATE_SPRING_APPLICATION); - builder.put(JavaCXFServerCodegen.USE_SPRING_ANNOTATION_CONFIG, USE_SPRING_ANNOTATION_CONFIG); - - builder.put(JavaCXFServerCodegen.USE_SWAGGER_FEATURE, USE_SWAGGER_FEATURE); - builder.put(JavaCXFServerCodegen.USE_SWAGGER_UI, USE_SWAGGER_UI); - - builder.put(JavaCXFServerCodegen.USE_WADL_FEATURE, USE_WADL_FEATURE); - builder.put(JavaCXFServerCodegen.USE_MULTIPART_FEATURE, USE_MULTIPART_FEATURE); - builder.put(JavaCXFServerCodegen.USE_GZIP_FEATURE, USE_GZIP_FEATURE); - builder.put(JavaCXFServerCodegen.USE_GZIP_FEATURE_FOR_TESTS, USE_GZIP_FEATURE_FOR_TESTS); - builder.put(JavaCXFServerCodegen.USE_LOGGING_FEATURE, USE_LOGGING_FEATURE); - builder.put(JavaCXFServerCodegen.USE_LOGGING_FEATURE_FOR_TESTS, USE_LOGGING_FEATURE_FOR_TESTS); - builder.put(JavaCXFServerCodegen.USE_BEANVALIDATION_FEATURE, USE_BEANVALIDATION_FEATURE); - builder.put(JavaCXFServerCodegen.USE_GENERIC_RESPONSE, USE_GENERIC_RESPONSE); - - builder.put(JavaCXFServerCodegen.GENERATE_SPRING_BOOT_APPLICATION, GENERATE_SPRING_BOOT_APPLICATION); - - builder.put(JavaCXFServerCodegen.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); - - builder.put(JavaCXFServerCodegen.ADD_CONSUMES_PRODUCES_JSON, ADD_CONSUMES_PRODUCES_JSON); - - builder.put(JavaCXFServerCodegen.USE_ANNOTATED_BASE_PATH, USE_ANNOTATED_BASE_PATH); - - builder.put(JavaCXFServerCodegen.GENERATE_NON_SPRING_APPLICATION, GENERATE_NON_SPRING_APPLICATION); - builder.put("serverPort", "3456"); - - return builder.build(); - - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java deleted file mode 100644 index 4444251d18a9..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.JavaClientCodegen; - -import java.util.HashMap; -import java.util.Map; - -public class JavaClientOptionsProvider extends JavaOptionsProvider { - - public static final String PERFORM_BEANVALIDATION = "false"; - - public static final String DEFAULT_LIBRARY_VALUE = "jersey2"; - - @Override - public Map createOptions() { - Map options = new HashMap(super.createOptions()); - options.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE); - options.put(JavaClientCodegen.USE_RX_JAVA, "false"); - options.put(JavaClientCodegen.USE_RX_JAVA2, "false"); - options.put(JavaClientCodegen.USE_PLAY_WS, "false"); - options.put(JavaClientCodegen.PLAY_VERSION, JavaClientCodegen.PLAY_25); - options.put(JavaClientCodegen.PARCELABLE_MODEL, "false"); - options.put(JavaClientCodegen.SUPPORT_JAVA6, "false"); - options.put(JavaClientCodegen.USE_BEANVALIDATION, "false"); - options.put(JavaClientCodegen.PERFORM_BEANVALIDATION, PERFORM_BEANVALIDATION); - options.put(JavaClientCodegen.USE_GZIP_FEATURE, "false"); - options.put(JavaClientCodegen.USE_RUNTIME_EXCEPTION, "false"); - options.put(JavaClientCodegen.JAVA8_MODE, "false"); - return options; - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaInflectorServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaInflectorServerOptionsProvider.java deleted file mode 100644 index a16b1a80368f..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaInflectorServerOptionsProvider.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.openapitools.codegen.options; - -public class JavaInflectorServerOptionsProvider extends JavaOptionsProvider { - @Override - public String getLanguage() { - return "inflector"; - } - - @Override - public boolean isServer() { - return true; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java deleted file mode 100644 index 071b1bd8b6c1..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.openapitools.codegen.options; - -import com.google.common.collect.ImmutableMap; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.JavaClientCodegen; - -import java.util.Map; - -public class JavaOptionsProvider implements OptionsProvider { - public static final String ARTIFACT_ID_VALUE = "swagger-java-client-test"; - public static final String MODEL_PACKAGE_VALUE = "package"; - public static final String API_PACKAGE_VALUE = "apiPackage"; - public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; - public static final String LICENSE_NAME_VALUE = "Apache License, Version 2.0"; - public static final String LICENSE_URL_VALUE = "http://www.apache.org/licenses/LICENSE-2.0"; - public static final String DEVELOPER_NAME_VALUE = "Swagger"; - public static final String DEVELOPER_EMAIL_VALUE = "apiteam@swagger.io"; - public static final String DEVELOPER_ORGANIZATION_VALUE = "Swagger"; - public static final String DEVELOPER_ORGANIZATION_URL_VALUE = "http://swagger.io"; - public static final String SCM_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; - public static final String SCM_DEVELOPER_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; - public static final String SCM_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String GROUP_ID_VALUE = "io.swagger.test"; - public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String ARTIFACT_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; - public static final String ARTIFACT_DESCRIPTION_VALUE = "Swagger Java Client Test"; - public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; - public static final String LOCAL_PREFIX_VALUE = "tst"; - public static final String SERIALIZABLE_MODEL_VALUE = "false"; - public static final String FULL_JAVA_UTIL_VALUE = "true"; - public static final String WITH_XML_VALUE = "false"; - public static final String JAVA8_MODE_VALUE = "true"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - //public static final String SUPPORT_JAVA6 = "true"; - public static final String USE_BEANVALIDATION = "false"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - private ImmutableMap options; - - /** - * Create an options provider with the default options. - */ - public JavaOptionsProvider() { - options = new ImmutableMap.Builder() - .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) - .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) - .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) - .put(CodegenConstants.ARTIFACT_URL, ARTIFACT_URL_VALUE) - .put(CodegenConstants.ARTIFACT_DESCRIPTION, ARTIFACT_DESCRIPTION_VALUE) - .put(CodegenConstants.SCM_CONNECTION, SCM_CONNECTION_VALUE) - .put(CodegenConstants.SCM_DEVELOPER_CONNECTION, SCM_DEVELOPER_CONNECTION_VALUE) - .put(CodegenConstants.SCM_URL, SCM_URL_VALUE) - .put(CodegenConstants.DEVELOPER_NAME, DEVELOPER_NAME_VALUE) - .put(CodegenConstants.DEVELOPER_EMAIL, DEVELOPER_EMAIL_VALUE) - .put(CodegenConstants.DEVELOPER_ORGANIZATION, DEVELOPER_ORGANIZATION_VALUE) - .put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, DEVELOPER_ORGANIZATION_URL_VALUE) - .put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE) - .put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) - .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) - .put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE) - .put(JavaClientCodegen.WITH_XML, WITH_XML_VALUE) - .put(JavaClientCodegen.JAVA8_MODE, JAVA8_MODE_VALUE) - .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") - .put(JavaClientCodegen.DATE_LIBRARY, "joda") - .put("hideGenerationTimestamp", "true") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - //.put("supportJava6", "true") - .build(); - } - - /** - * Use the default options, but override the ones found in additionalOptions. - */ - public JavaOptionsProvider(Map additionalOptions) { - options = new ImmutableMap.Builder() - .putAll(options) - .putAll(additionalOptions) - .build(); - } - - @Override - public Map createOptions() { - return options; - } - - @Override - public boolean isServer() { - return false; - } - - @Override - public String getLanguage() { - return "java"; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaPlayFrameworkOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaPlayFrameworkOptionsProvider.java deleted file mode 100644 index 13e48b59183c..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaPlayFrameworkOptionsProvider.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.languages.JavaPlayFrameworkCodegen; - -import java.util.HashMap; -import java.util.Map; - -public class JavaPlayFrameworkOptionsProvider extends JavaOptionsProvider { - public static final String TITLE = "swagger"; - public static final String CONFIG_PACKAGE_VALUE = "configPackage"; - public static final String BASE_PACKAGE_VALUE = "basePackage"; - public static final String CONTROLLER_ONLY = "false"; - public static final String USE_BEANVALIDATION = "true"; - public static final String USE_INTERFACES = "true"; - public static final String HANDLE_EXCEPTIONS = "true"; - public static final String WRAP_CALLS = "true"; - public static final String USE_SWAGGER_UI = "true"; - - @Override - public String getLanguage() { - return "java-play-framework"; - } - - @Override - public Map createOptions() { - Map options = new HashMap(super.createOptions()); - options.put(JavaPlayFrameworkCodegen.TITLE, TITLE); - options.put(JavaPlayFrameworkCodegen.CONFIG_PACKAGE, CONFIG_PACKAGE_VALUE); - options.put(JavaPlayFrameworkCodegen.BASE_PACKAGE, BASE_PACKAGE_VALUE); - options.put(JavaPlayFrameworkCodegen.CONTROLLER_ONLY, CONTROLLER_ONLY); - options.put(JavaPlayFrameworkCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION); - options.put(JavaPlayFrameworkCodegen.USE_INTERFACES, USE_INTERFACES); - options.put(JavaPlayFrameworkCodegen.HANDLE_EXCEPTIONS, HANDLE_EXCEPTIONS); - options.put(JavaPlayFrameworkCodegen.WRAP_CALLS, WRAP_CALLS); - options.put(JavaPlayFrameworkCodegen.USE_SWAGGER_UI, USE_SWAGGER_UI); - - return options; - } - - @Override - public boolean isServer() { - return true; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaResteasyEapServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaResteasyEapServerOptionsProvider.java deleted file mode 100644 index 41a626aa3f72..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaResteasyEapServerOptionsProvider.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.openapitools.codegen.options; - -import java.util.Map; - -import com.google.common.collect.ImmutableMap; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.JavaCXFServerCodegen; -import org.openapitools.codegen.languages.JavaResteasyEapServerCodegen; -import org.openapitools.codegen.languages.JavaResteasyServerCodegen; - -public class JavaResteasyEapServerOptionsProvider extends JavaOptionsProvider { - - public static final String GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR = "true"; - - public static final String IMPL_FOLDER_VALUE = "src/main/java"; - - public static final String USE_BEANVALIDATION = "true"; - - public static final String USE_SWAGGER_FEATURE = "true"; - - @Override - public boolean isServer() { - return true; - } - - @Override - public String getLanguage() { - return "jaxrs-resteasy-eap"; - } - - @Override - public Map createOptions() { - - Map parentOptions = super.createOptions(); - - ImmutableMap.Builder builder = new ImmutableMap.Builder() - .putAll(parentOptions); - - builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE); - builder.put("title", "Test title"); - - builder.put(JavaCXFServerCodegen.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); - builder.put(JavaResteasyServerCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION); - builder.put(JavaResteasyEapServerCodegen.USE_SWAGGER_FEATURE, USE_SWAGGER_FEATURE); - builder.put("serverPort", "1234"); - - return builder.build(); - - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java deleted file mode 100644 index 6d0e3bf77987..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.openapitools.codegen.options; - -import java.util.Map; - -import com.google.common.collect.ImmutableMap; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.JavaCXFServerCodegen; -import org.openapitools.codegen.languages.JavaResteasyServerCodegen; - -public class JavaResteasyServerOptionsProvider extends JavaOptionsProvider { - - public static final String GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR = "true"; - - public static final String IMPL_FOLDER_VALUE = "src/main/java"; - - public static final String USE_BEANVALIDATION = "true"; - - @Override - public boolean isServer() { - return true; - } - - @Override - public String getLanguage() { - return "jaxrs-resteasy"; - } - - @Override - public Map createOptions() { - - Map parentOptions = super.createOptions(); - - ImmutableMap.Builder builder = new ImmutableMap.Builder() - .putAll(parentOptions); - - builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE); - builder.put("title", "Test title"); - - builder.put(JavaCXFServerCodegen.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); - builder.put(JavaResteasyServerCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION); - builder.put("serverPort", "1234"); - - return builder.build(); - - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java deleted file mode 100644 index 46851dce7707..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.JavascriptClientCodegen; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class JavaScriptOptionsProvider implements OptionsProvider { - public static final String ARTIFACT_ID_VALUE = "swagger-javascript-client-test"; - public static final String INVOKER_PACKAGE_VALUE = "invoker"; - public static final String MODEL_PACKAGE_VALUE = "model"; - public static final String API_PACKAGE_VALUE = "api"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String GROUP_ID_VALUE = "io.swagger.test"; - public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String SOURCE_FOLDER_VALUE = "src/main/javascript"; - public static final String LOCAL_PREFIX_VALUE = "_"; -// public static final String SERIALIZABLE_MODEL_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String PROJECT_NAME_VALUE = "JavaScript Client Test"; - public static final String MODULE_NAME_VALUE = "JavaScriptClient"; - public static final String PROJECT_DESCRIPTION_VALUE = "Tests JavaScript code generator options"; - public static final String PROJECT_VERSION_VALUE = "1.0.0"; - public static final String PROJECT_LICENSE_NAME_VALUE = "Apache"; - public static final String USE_PROMISES_VALUE = "true"; - public static final String USE_INHERITANCE_VALUE = "false"; - public static final String EMIT_MODEL_METHODS_VALUE = "true"; - public static final String EMIT_JS_DOC_VALUE = "false"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - public static final String USE_ES6_VALUE = "true"; - - - private ImmutableMap options; - - /** - * Create an options provider with the default options. - */ - public JavaScriptOptionsProvider() { - // Commented generic options not yet supported by JavaScript codegen. - options = new ImmutableMap.Builder() - .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) -// .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) -// .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) -// .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) -// .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") - .put(JavascriptClientCodegen.PROJECT_NAME, PROJECT_NAME_VALUE) - .put(JavascriptClientCodegen.MODULE_NAME, MODULE_NAME_VALUE) - .put(JavascriptClientCodegen.PROJECT_DESCRIPTION, PROJECT_DESCRIPTION_VALUE) - .put(JavascriptClientCodegen.PROJECT_VERSION, PROJECT_VERSION_VALUE) - .put(CodegenConstants.LICENSE_NAME, PROJECT_LICENSE_NAME_VALUE) - .put(JavascriptClientCodegen.USE_PROMISES, USE_PROMISES_VALUE) - .put(JavascriptClientCodegen.USE_INHERITANCE, USE_INHERITANCE_VALUE) - .put(JavascriptClientCodegen.EMIT_MODEL_METHODS, EMIT_MODEL_METHODS_VALUE) - .put(JavascriptClientCodegen.EMIT_JS_DOC, EMIT_JS_DOC_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .put(JavascriptClientCodegen.USE_ES6, USE_ES6_VALUE) - .build(); - } - - /** - * Use the default options, but override the ones found in additionalOptions. - */ - public JavaScriptOptionsProvider(Map additionalOptions) { - options = new ImmutableMap.Builder() - .putAll(options) - .putAll(additionalOptions) - .build(); - } - - @Override - public Map createOptions() { - return options; - } - - @Override - public boolean isServer() { - return false; - } - - @Override - public String getLanguage() { - return "javascript"; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaUndertowServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaUndertowServerOptionsProvider.java deleted file mode 100644 index 30b89fdcd8cc..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavaUndertowServerOptionsProvider.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.openapitools.codegen.options; - -/** - * Created by steve on 18/09/16. - */ -public class JavaUndertowServerOptionsProvider extends JavaOptionsProvider { - @Override - public String getLanguage() { - return "undertow"; - } - - @Override - public boolean isServer() { - return true; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java deleted file mode 100644 index b2a7dae1a0aa..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class JavascriptClosureAnularClientOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "javascript-closure-angular"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java deleted file mode 100644 index 2f1dbd35c41d..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java +++ /dev/null @@ -1,99 +0,0 @@ -package org.openapitools.codegen.options; - -import com.google.common.collect.ImmutableMap; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.JavaCXFServerCodegen; -import org.openapitools.codegen.languages.JavaClientCodegen; -import org.openapitools.codegen.languages.JavaJerseyServerCodegen; - -import java.util.Map; - -public class JaxRSServerOptionsProvider implements OptionsProvider { - public static final String ARTIFACT_ID_VALUE = "swagger-java-client-test"; - public static final String MODEL_PACKAGE_VALUE = "package"; - public static final String API_PACKAGE_VALUE = "apiPackage"; - public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String GROUP_ID_VALUE = "io.swagger.test"; - public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String ARTIFACT_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; - public static final String ARTIFACT_DESCRIPTION_VALUE = "Swagger Java Client Test"; - public static final String DEVELOPER_NAME_VALUE = "Swagger"; - public static final String DEVELOPER_EMAIL_VALUE = "apiteam@swagger.io"; - public static final String DEVELOPER_ORGANIZATION_VALUE = "Swagger"; - public static final String DEVELOPER_ORGANIZATION_URL_VALUE = "http://swagger.io"; - public static final String SCM_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; - public static final String SCM_DEVELOPER_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; - public static final String SCM_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; - public static final String LICENSE_NAME_VALUE = "Apache License, Version 2.0"; - public static final String LICENSE_URL_VALUE = "http://www.apache.org/licenses/LICENSE-2.0"; - public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; - public static final String LOCAL_PREFIX_VALUE = "tst"; - public static final String DEFAULT_LIBRARY_VALUE = "jersey2"; - public static final String SERIALIZABLE_MODEL_VALUE = "false"; - public static final String FULL_JAVA_UTIL_VALUE = "true"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String JODA_DATE_LIBRARY = "joda"; - public static final String IMPL_FOLDER_VALUE = "src/main/java/impl"; - public static final String JAXRS_DEFAULT_LIBRARY_VALUE = "jersey1"; - public static final String USE_BEANVALIDATION = "true"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - public static final String JAVA8_MODE_VALUE = "false"; - public static final String WITH_XML_VALUE = "false"; - public static final String USE_TAGS = "useTags"; - - - @Override - public boolean isServer() { - return true; - } - - @Override - public String getLanguage() { - return "jaxrs"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE) - .put(JavaClientCodegen.DATE_LIBRARY, "joda") //java.lang.IllegalArgumentException: Multiple entries with same key: dateLibrary=joda and dateLibrary=joda - .put(JavaClientCodegen.SUPPORT_JAVA6, "false") - .put("title", "Test title") - .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) - .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) - .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) - .put(CodegenConstants.ARTIFACT_URL, ARTIFACT_URL_VALUE) - .put(CodegenConstants.ARTIFACT_DESCRIPTION, ARTIFACT_DESCRIPTION_VALUE) - .put(CodegenConstants.SCM_CONNECTION, SCM_CONNECTION_VALUE) - .put(CodegenConstants.SCM_DEVELOPER_CONNECTION, SCM_DEVELOPER_CONNECTION_VALUE) - .put(CodegenConstants.SCM_URL, SCM_URL_VALUE) - .put(CodegenConstants.DEVELOPER_NAME, DEVELOPER_NAME_VALUE) - .put(CodegenConstants.DEVELOPER_EMAIL, DEVELOPER_EMAIL_VALUE) - .put(CodegenConstants.DEVELOPER_ORGANIZATION, DEVELOPER_ORGANIZATION_VALUE) - .put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, DEVELOPER_ORGANIZATION_URL_VALUE) - .put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE) - .put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) - .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) - .put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE) - .put(CodegenConstants.LIBRARY, JAXRS_DEFAULT_LIBRARY_VALUE) - .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") - .put(JavaClientCodegen.JAVA8_MODE, JAVA8_MODE_VALUE) - .put(JavaClientCodegen.WITH_XML, WITH_XML_VALUE) - //.put(JavaClientCodegen.DATE_LIBRARY, "joda") - .put("hideGenerationTimestamp", "true") - .put(JavaCXFServerCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION) - .put("serverPort", "2345") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .put(JavaJerseyServerCodegen.USE_TAGS, USE_TAGS); - - return builder.build(); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/KotlinClientCodegenOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/KotlinClientCodegenOptionsProvider.java deleted file mode 100644 index be02fdd91815..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/KotlinClientCodegenOptionsProvider.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; -import org.openapitools.codegen.languages.KotlinClientCodegen; - -import java.util.Map; - -public class KotlinClientCodegenOptionsProvider implements OptionsProvider { - public static final String PACKAGE_NAME_VALUE = "io.swagger.tests.kotlin"; - public static final String ARTIFACT_VERSION_VALUE = "0.0.1-SNAPSHOT"; - public static final String ARTIFACT_ID = "swagger-kotlin-test"; - public static final String GROUP_ID = "io.swagger.tests"; - public static final String SOURCE_FOLDER = "./generated/kotlin"; - public static final String ENUM_PROPERTY_NAMING = "camelCase"; - public static final String DATE_LIBRARY = KotlinClientCodegen.DateLibrary.JAVA8.value; - - @Override - public String getLanguage() { - return "kotlin"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder - .put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) - .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) - .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID) - .put(CodegenConstants.GROUP_ID, GROUP_ID) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER) - .put(CodegenConstants.ENUM_PROPERTY_NAMING, ENUM_PROPERTY_NAMING) - .put(KotlinClientCodegen.DATE_LIBRARY, DATE_LIBRARY) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} - diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java deleted file mode 100644 index ba063c0bb3f9..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.openapitools.codegen.options; - -import java.util.Map; - -import com.google.common.collect.ImmutableMap; - -import static org.openapitools.codegen.CodegenConstants.*; - -public class NancyFXServerOptionsProvider implements OptionsProvider { - public static final String PACKAGE_NAME_VALUE = "swagger_server_nancyfx"; - public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String SOURCE_FOLDER_VALUE = "src_nancyfx"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - public static final String PROJECT_GUID_VALUE = "{6885796E-A4C1-48EA-9766-CCD1563C90DF}"; - - - @Override - public String getLanguage() { - return "nancyfx"; - } - - @Override - public Map createOptions() { - final ImmutableMap.Builder builder = ImmutableMap.builder(); - return builder.put(PACKAGE_NAME, PACKAGE_NAME_VALUE) - .put(PACKAGE_VERSION, PACKAGE_VERSION_VALUE) - .put(SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(SORT_PARAMS_BY_REQUIRED_FLAG, "true") - .put(OPTIONAL_PROJECT_GUID, PROJECT_GUID_VALUE) - .put(USE_DATETIME_OFFSET, "true") - .put(USE_COLLECTION, "false") - .put(RETURN_ICOLLECTION, "false") - .put(INTERFACE_PREFIX, "X") - .put(ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - - .build(); - } - - @Override - public boolean isServer() { - return true; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java deleted file mode 100644 index 1b841a8d8bae..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.NodeJSServerCodegen; -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class NodeJSServerOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String GOOGLE_CLOUD_FUNCTIONS = "false"; - public static final String EXPORTED_NAME = "exported"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "nodejs-server"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(NodeJSServerCodegen.GOOGLE_CLOUD_FUNCTIONS, GOOGLE_CLOUD_FUNCTIONS) - .put(NodeJSServerCodegen.EXPORTED_NAME, EXPORTED_NAME) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return true; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Qt5CPPOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Qt5CPPOptionsProvider.java deleted file mode 100644 index 3aa2519db45b..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Qt5CPPOptionsProvider.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; -import org.openapitools.codegen.languages.Qt5CPPGenerator; - -import java.util.Map; - -public class Qt5CPPOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - public static final String CPP_NAMESPACE_VALUE = "Swagger"; - - - @Override - public String getLanguage() { - return "qt5cpp"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .put(Qt5CPPGenerator.CPP_NAMESPACE, CPP_NAMESPACE_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java deleted file mode 100644 index 9d75f9c21309..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.openapitools.codegen.options; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class Rails5ServerOptionsProvider implements OptionsProvider { - @Override - public String getLanguage() { - return "Rails5"; - } - - @Override - public Map createOptions() { - //Rails5ServerCodegen doesn't have its own options and base options are cleared - return ImmutableMap.of(); - } - - @Override - public boolean isServer() { - return true; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/RustClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/RustClientOptionsProvider.java deleted file mode 100644 index 92559f25d2fc..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/RustClientOptionsProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.RustClientCodegen; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class RustClientOptionsProvider implements OptionsProvider { - public static final String PACKAGE_NAME_VALUE = "swagger_test"; - public static final String PACKAGE_VERSION_VALUE = "2.1.2"; - - - @Override - public String getLanguage() { - return "rust"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(RustClientCodegen.PACKAGE_NAME, PACKAGE_NAME_VALUE) - .put(RustClientCodegen.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/RustServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/RustServerOptionsProvider.java deleted file mode 100644 index 5282e74a01ca..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/RustServerOptionsProvider.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.openapitools.codegen.options; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class RustServerOptionsProvider implements OptionsProvider { - @Override - public String getLanguage() { - return "rust-server"; - } - - @Override - public Map createOptions() { - return ImmutableMap.of(); - } - - @Override - public boolean isServer() { - return true; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java deleted file mode 100644 index 158b45efe122..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class ScalaClientOptionsProvider implements OptionsProvider { - public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; - public static final String MODEL_PACKAGE_VALUE = "package"; - public static final String API_PACKAGE_VALUE = "apiPackage"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "scala"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java deleted file mode 100644 index ca881d1f1dc8..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class ScalatraServerOptionsProvider implements OptionsProvider { - public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; - public static final String MODEL_PACKAGE_VALUE = "package"; - public static final String API_PACKAGE_VALUE = "apiPackage"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "scalatra"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return true; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java deleted file mode 100644 index 4fe3a9078ba9..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.SpringCodegen; - -import java.util.HashMap; -import java.util.Map; - -public class SpringOptionsProvider extends JavaOptionsProvider { - public static final String TITLE = "swagger"; - public static final String CONFIG_PACKAGE_VALUE = "configPackage"; - public static final String BASE_PACKAGE_VALUE = "basePackage"; - public static final String LIBRARY_VALUE = "spring-mvc"; //FIXME hidding value from super class - public static final String INTERFACE_ONLY = "true"; - public static final String DELEGATE_PATTERN = "true"; - public static final String SINGLE_CONTENT_TYPES = "true"; - public static final String JAVA_8 = "true"; - public static final String ASYNC = "true"; - public static final String RESPONSE_WRAPPER = "Callable"; - public static final String USE_TAGS = "useTags"; - public static final String USE_BEANVALIDATION = "false"; - public static final String IMPLICIT_HEADERS = "false"; - public static final String SWAGGER_DOCKET_CONFIG = "false"; - public static final String USE_OPTIONAL = "false"; - - @Override - public String getLanguage() { - return "spring"; - } - - @Override - public Map createOptions() { - Map options = new HashMap(super.createOptions()); - options.put(SpringCodegen.TITLE, TITLE); - options.put(SpringCodegen.CONFIG_PACKAGE, CONFIG_PACKAGE_VALUE); - options.put(SpringCodegen.BASE_PACKAGE, BASE_PACKAGE_VALUE); - options.put(CodegenConstants.LIBRARY, LIBRARY_VALUE); - options.put(SpringCodegen.INTERFACE_ONLY, INTERFACE_ONLY); - options.put(SpringCodegen.DELEGATE_PATTERN, DELEGATE_PATTERN); - options.put(SpringCodegen.SINGLE_CONTENT_TYPES, SINGLE_CONTENT_TYPES); - options.put(SpringCodegen.JAVA_8, JAVA_8); - options.put(SpringCodegen.ASYNC, ASYNC); - options.put(SpringCodegen.RESPONSE_WRAPPER, RESPONSE_WRAPPER); - options.put(SpringCodegen.USE_TAGS, USE_TAGS); - options.put(SpringCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION); - options.put(SpringCodegen.IMPLICIT_HEADERS, IMPLICIT_HEADERS); - options.put(SpringCodegen.SWAGGER_DOCKET_CONFIG, SWAGGER_DOCKET_CONFIG); - options.put(SpringCodegen.USE_OPTIONAL, USE_OPTIONAL); - - return options; - } - - @Override - public boolean isServer() { - return true; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/StaticDocOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/StaticDocOptionsProvider.java deleted file mode 100644 index 9cdd171ca2a0..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/StaticDocOptionsProvider.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class StaticDocOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String ARTIFACT_ID_VALUE = "swagger-java-client-test"; - public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; - public static final String GROUP_ID_VALUE = "io.swagger.test"; - public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "dynamic-html"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) - .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) - .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java deleted file mode 100644 index e1fe7ad206b6..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class StaticHtmlOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String ARTIFACT_ID_VALUE = "swagger-java-client-test"; - public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; - public static final String GROUP_ID_VALUE = "io.swagger.test"; - public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "html"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put("appName", "Swagger Sample") - .put("appDescription", "A sample swagger server") - .put("infoUrl", "https://helloreverb.com") - .put("infoEmail", "hello@helloreverb.com") - .put("licenseInfo", "All rights reserved") - .put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html") - .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) - .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) - .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SwaggerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SwaggerOptionsProvider.java deleted file mode 100644 index eb3c10eb4e26..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SwaggerOptionsProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class SwaggerOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "swagger"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java deleted file mode 100644 index 0826f22342c2..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class SwaggerYamlOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - @Override - public String getLanguage() { - return "swagger-yaml"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put("outputFile", "swagger.yaml") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Swift3OptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Swift3OptionsProvider.java deleted file mode 100644 index c1203161ae3e..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Swift3OptionsProvider.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.Swift3Codegen; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class Swift3OptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String PROJECT_NAME_VALUE = "Swagger"; - public static final String RESPONSE_AS_VALUE = "test"; - public static final String UNWRAP_REQUIRED_VALUE = "true"; - public static final String OBJC_COMPATIBLE_VALUE = "false"; - public static final String LENIENT_TYPE_CAST_VALUE = "false"; - public static final String POD_SOURCE_VALUE = "{ :git => 'git@github.com:swagger-api/swagger-mustache.git'," + - " :tag => 'v1.0.0-SNAPSHOT' }"; - public static final String POD_VERSION_VALUE = "v1.0.0-SNAPSHOT"; - public static final String POD_AUTHORS_VALUE = "podAuthors"; - public static final String POD_SOCIAL_MEDIA_URL_VALUE = "podSocialMediaURL"; - public static final String POD_DOCSET_URL_VALUE = "podDocsetURL"; - public static final String POD_LICENSE_VALUE = "'Apache License, Version 2.0'"; - public static final String POD_HOMEPAGE_VALUE = "podHomepage"; - public static final String POD_SUMMARY_VALUE = "podSummary"; - public static final String POD_DESCRIPTION_VALUE = "podDescription"; - public static final String POD_SCREENSHOTS_VALUE = "podScreenshots"; - public static final String POD_DOCUMENTATION_URL_VALUE = "podDocumentationURL"; - public static final String SWIFT_USE_API_NAMESPACE_VALUE = "swiftUseApiNamespace"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - @Override - public String getLanguage() { - return "swift"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(Swift3Codegen.PROJECT_NAME, PROJECT_NAME_VALUE) - .put(Swift3Codegen.RESPONSE_AS, RESPONSE_AS_VALUE) - .put(Swift3Codegen.UNWRAP_REQUIRED, UNWRAP_REQUIRED_VALUE) - .put(Swift3Codegen.OBJC_COMPATIBLE, OBJC_COMPATIBLE_VALUE) - .put(Swift3Codegen.LENIENT_TYPE_CAST, LENIENT_TYPE_CAST_VALUE) - .put(Swift3Codegen.POD_SOURCE, POD_SOURCE_VALUE) - .put(CodegenConstants.POD_VERSION, POD_VERSION_VALUE) - .put(Swift3Codegen.POD_AUTHORS, POD_AUTHORS_VALUE) - .put(Swift3Codegen.POD_SOCIAL_MEDIA_URL, POD_SOCIAL_MEDIA_URL_VALUE) - .put(Swift3Codegen.POD_DOCSET_URL, POD_DOCSET_URL_VALUE) - .put(Swift3Codegen.POD_LICENSE, POD_LICENSE_VALUE) - .put(Swift3Codegen.POD_HOMEPAGE, POD_HOMEPAGE_VALUE) - .put(Swift3Codegen.POD_SUMMARY, POD_SUMMARY_VALUE) - .put(Swift3Codegen.POD_DESCRIPTION, POD_DESCRIPTION_VALUE) - .put(Swift3Codegen.POD_SCREENSHOTS, POD_SCREENSHOTS_VALUE) - .put(Swift3Codegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE) - .put(Swift3Codegen.SWIFT_USE_API_NAMESPACE, SWIFT_USE_API_NAMESPACE_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Swift4OptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Swift4OptionsProvider.java deleted file mode 100644 index 9b8281f31010..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/Swift4OptionsProvider.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.Swift4Codegen; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class Swift4OptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String PROJECT_NAME_VALUE = "Swagger"; - public static final String RESPONSE_AS_VALUE = "test"; - public static final String UNWRAP_REQUIRED_VALUE = "true"; - public static final String OBJC_COMPATIBLE_VALUE = "false"; - public static final String LENIENT_TYPE_CAST_VALUE = "false"; - public static final String POD_SOURCE_VALUE = "{ :git => 'git@github.com:swagger-api/swagger-mustache.git'," + - " :tag => 'v1.0.0-SNAPSHOT' }"; - public static final String POD_VERSION_VALUE = "v1.0.0-SNAPSHOT"; - public static final String POD_AUTHORS_VALUE = "podAuthors"; - public static final String POD_SOCIAL_MEDIA_URL_VALUE = "podSocialMediaURL"; - public static final String POD_DOCSET_URL_VALUE = "podDocsetURL"; - public static final String POD_LICENSE_VALUE = "'Apache License, Version 2.0'"; - public static final String POD_HOMEPAGE_VALUE = "podHomepage"; - public static final String POD_SUMMARY_VALUE = "podSummary"; - public static final String POD_DESCRIPTION_VALUE = "podDescription"; - public static final String POD_SCREENSHOTS_VALUE = "podScreenshots"; - public static final String POD_DOCUMENTATION_URL_VALUE = "podDocumentationURL"; - public static final String SWIFT_USE_API_NAMESPACE_VALUE = "swiftUseApiNamespace"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - @Override - public String getLanguage() { - return "swift4"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(Swift4Codegen.PROJECT_NAME, PROJECT_NAME_VALUE) - .put(Swift4Codegen.RESPONSE_AS, RESPONSE_AS_VALUE) - .put(Swift4Codegen.UNWRAP_REQUIRED, UNWRAP_REQUIRED_VALUE) - .put(Swift4Codegen.OBJC_COMPATIBLE, OBJC_COMPATIBLE_VALUE) - .put(Swift4Codegen.LENIENT_TYPE_CAST, LENIENT_TYPE_CAST_VALUE) - .put(Swift4Codegen.POD_SOURCE, POD_SOURCE_VALUE) - .put(CodegenConstants.POD_VERSION, POD_VERSION_VALUE) - .put(Swift4Codegen.POD_AUTHORS, POD_AUTHORS_VALUE) - .put(Swift4Codegen.POD_SOCIAL_MEDIA_URL, POD_SOCIAL_MEDIA_URL_VALUE) - .put(Swift4Codegen.POD_DOCSET_URL, POD_DOCSET_URL_VALUE) - .put(Swift4Codegen.POD_LICENSE, POD_LICENSE_VALUE) - .put(Swift4Codegen.POD_HOMEPAGE, POD_HOMEPAGE_VALUE) - .put(Swift4Codegen.POD_SUMMARY, POD_SUMMARY_VALUE) - .put(Swift4Codegen.POD_DESCRIPTION, POD_DESCRIPTION_VALUE) - .put(Swift4Codegen.POD_SCREENSHOTS, POD_SCREENSHOTS_VALUE) - .put(Swift4Codegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE) - .put(Swift4Codegen.SWIFT_USE_API_NAMESPACE, SWIFT_USE_API_NAMESPACE_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java deleted file mode 100644 index b21590c06f0a..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.SwiftCodegen; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class SwiftOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String PROJECT_NAME_VALUE = "Swagger"; - public static final String RESPONSE_AS_VALUE = "test"; - public static final String UNWRAP_REQUIRED_VALUE = "true"; - public static final String POD_SOURCE_VALUE = "{ :git => 'git@github.com:swagger-api/swagger-mustache.git'," + - " :tag => 'v1.0.0-SNAPSHOT' }"; - public static final String POD_VERSION_VALUE = "v1.0.0-SNAPSHOT"; - public static final String POD_AUTHORS_VALUE = "podAuthors"; - public static final String POD_SOCIAL_MEDIA_URL_VALUE = "podSocialMediaURL"; - public static final String POD_DOCSET_URL_VALUE = "podDocsetURL"; - public static final String POD_LICENSE_VALUE = "'Apache License, Version 2.0'"; - public static final String POD_HOMEPAGE_VALUE = "podHomepage"; - public static final String POD_SUMMARY_VALUE = "podSummary"; - public static final String POD_DESCRIPTION_VALUE = "podDescription"; - public static final String POD_SCREENSHOTS_VALUE = "podScreenshots"; - public static final String POD_DOCUMENTATION_URL_VALUE = "podDocumentationURL"; - public static final String SWIFT_USE_API_NAMESPACE_VALUE = "swiftUseApiNamespace"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "swift"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(SwiftCodegen.PROJECT_NAME, PROJECT_NAME_VALUE) - .put(SwiftCodegen.RESPONSE_AS, RESPONSE_AS_VALUE) - .put(SwiftCodegen.UNWRAP_REQUIRED, UNWRAP_REQUIRED_VALUE) - .put(SwiftCodegen.POD_SOURCE, POD_SOURCE_VALUE) - .put(CodegenConstants.POD_VERSION, POD_VERSION_VALUE) - .put(SwiftCodegen.POD_AUTHORS, POD_AUTHORS_VALUE) - .put(SwiftCodegen.POD_SOCIAL_MEDIA_URL, POD_SOCIAL_MEDIA_URL_VALUE) - .put(SwiftCodegen.POD_DOCSET_URL, POD_DOCSET_URL_VALUE) - .put(SwiftCodegen.POD_LICENSE, POD_LICENSE_VALUE) - .put(SwiftCodegen.POD_HOMEPAGE, POD_HOMEPAGE_VALUE) - .put(SwiftCodegen.POD_SUMMARY, POD_SUMMARY_VALUE) - .put(SwiftCodegen.POD_DESCRIPTION, POD_DESCRIPTION_VALUE) - .put(SwiftCodegen.POD_SCREENSHOTS, POD_SCREENSHOTS_VALUE) - .put(SwiftCodegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE) - .put(SwiftCodegen.SWIFT_USE_API_NAMESPACE, SWIFT_USE_API_NAMESPACE_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SymfonyServerOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SymfonyServerOptionsProvider.java deleted file mode 100644 index e03502ac89fd..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SymfonyServerOptionsProvider.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.openapitools.codegen.options; - -import com.google.common.collect.ImmutableMap; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.SymfonyServerCodegen; -import org.openapitools.codegen.languages.SymfonyServerCodegen; - -import java.util.Map; - -public class SymfonyServerOptionsProvider implements OptionsProvider { - public static final String BUNDLE_NAME_VALUE = "AcmeSwagger"; - public static final String MODEL_PACKAGE_VALUE = "package"; - public static final String API_PACKAGE_VALUE = "apiPackage"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String VARIABLE_NAMING_CONVENTION_VALUE = "snake_case"; - public static final String INVOKER_PACKAGE_VALUE = "Acme\\Bundle\\SwaggerBundle"; - public static final String PACKAGE_PATH_VALUE = "SwaggerClient-php"; - public static final String SRC_BASE_PATH_VALUE = "libPhp"; - public static final String COMPOSER_VENDOR_NAME_VALUE = "swaggerPhp"; - public static final String COMPOSER_PROJECT_NAME_VALUE = "swagger-client-php"; - public static final String GIT_USER_ID_VALUE = "gitSwaggerPhp"; - public static final String GIT_REPO_ID_VALUE = "git-swagger-client-php"; - public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "php-symfony"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(SymfonyServerCodegen.BUNDLE_NAME, BUNDLE_NAME_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(SymfonyServerCodegen.VARIABLE_NAMING_CONVENTION, VARIABLE_NAMING_CONVENTION_VALUE) - .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(SymfonyServerCodegen.PACKAGE_PATH, PACKAGE_PATH_VALUE) - .put(SymfonyServerCodegen.SRC_BASE_PATH, SRC_BASE_PATH_VALUE) - .put(SymfonyServerCodegen.COMPOSER_VENDOR_NAME, COMPOSER_VENDOR_NAME_VALUE) - .put(CodegenConstants.GIT_USER_ID, GIT_USER_ID_VALUE) - .put(SymfonyServerCodegen.COMPOSER_PROJECT_NAME, COMPOSER_PROJECT_NAME_VALUE) - .put(CodegenConstants.GIT_REPO_ID, GIT_REPO_ID_VALUE) - .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .put(SymfonyServerCodegen.PHP_LEGACY_SUPPORT, "true") - .build(); - } - - @Override - public boolean isServer() { - return true; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TizenClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TizenClientOptionsProvider.java deleted file mode 100644 index 376bf187141e..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TizenClientOptionsProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class TizenClientOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "tizen"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java deleted file mode 100644 index f4857973ed47..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.openapitools.codegen.options; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; - -public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { - public static final String SUPPORTS_ES6_VALUE = "false"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; - private static final String NMP_NAME = "npmName"; - private static final String NMP_VERSION = "1.1.2"; - private static final String NPM_REPOSITORY = "https://registry.npmjs.org"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - public static final String NG_VERSION = "2"; - - - @Override - public String getLanguage() { - return "typescript-angular"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) - .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) - .put(TypeScriptAngularClientCodegen.NPM_NAME, NMP_NAME) - .put(TypeScriptAngularClientCodegen.NPM_VERSION, NMP_VERSION) - .put(TypeScriptAngularClientCodegen.SNAPSHOT, Boolean.FALSE.toString()) - .put(TypeScriptAngularClientCodegen.WITH_INTERFACES, Boolean.FALSE.toString()) - .put(TypeScriptAngularClientCodegen.TAGGED_UNIONS, Boolean.FALSE.toString()) - .put(TypeScriptAngularClientCodegen.NPM_REPOSITORY, NPM_REPOSITORY) - .put(TypeScriptAngularClientCodegen.NG_VERSION, NG_VERSION) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptAngularJsClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptAngularJsClientOptionsProvider.java deleted file mode 100644 index 5644fea45141..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptAngularJsClientOptionsProvider.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.openapitools.codegen.options; - -import org.openapitools.codegen.CodegenConstants; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public class TypeScriptAngularJsClientOptionsProvider implements OptionsProvider { - public static final String SUPPORTS_ES6_VALUE = "false"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - @Override - public String getLanguage() { - return "typescript-angularjs"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptAureliaClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptAureliaClientOptionsProvider.java deleted file mode 100644 index 02e4e826110a..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptAureliaClientOptionsProvider.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.openapitools.codegen.options; - -import com.google.common.collect.ImmutableMap; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.TypeScriptAureliaClientCodegen; - -import java.util.Map; - -public class TypeScriptAureliaClientOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final Boolean SUPPORTS_ES6_VALUE = false; - public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; - private static final String NMP_NAME = "npmName"; - private static final String NMP_VERSION = "1.0.0"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "typescript-aurelia"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) - .put(CodegenConstants.SUPPORTS_ES6, String.valueOf(SUPPORTS_ES6_VALUE)) - .put(TypeScriptAureliaClientCodegen.NPM_NAME, NMP_NAME) - .put(TypeScriptAureliaClientCodegen.NPM_VERSION, NMP_VERSION) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java deleted file mode 100644 index 757c7d7f3da9..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.openapitools.codegen.options; - -import com.google.common.collect.ImmutableMap; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen; - -import java.util.Map; - -public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final Boolean SUPPORTS_ES6_VALUE = false; - public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; - private static final String NMP_NAME = "npmName"; - private static final String NMP_VERSION = "1.0.0"; - private static final String NPM_REPOSITORY = "https://registry.npmjs.org"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - - - @Override - public String getLanguage() { - return "typescript-fetch"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) - .put(CodegenConstants.SUPPORTS_ES6, String.valueOf(SUPPORTS_ES6_VALUE)) - .put(TypeScriptFetchClientCodegen.NPM_NAME, NMP_NAME) - .put(TypeScriptFetchClientCodegen.NPM_VERSION, NMP_VERSION) - .put(TypeScriptFetchClientCodegen.NPM_REPOSITORY, NPM_REPOSITORY) - .put(TypeScriptFetchClientCodegen.SNAPSHOT, Boolean.FALSE.toString()) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/phpsymfony/PhpSymfonyServerOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/phpsymfony/PhpSymfonyServerOptionsTest.java deleted file mode 100644 index 13d01f4d0afc..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/phpsymfony/PhpSymfonyServerOptionsTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.openapitools.codegen.phpsymfony; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.AbstractPhpCodegen; -import org.openapitools.codegen.languages.SymfonyServerCodegen; -import org.openapitools.codegen.options.SymfonyServerOptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class PhpSymfonyServerOptionsTest extends AbstractOptionsTest { - - @Tested - private SymfonyServerCodegen symfonyCodegen; - - public PhpSymfonyServerOptionsTest() { - super(new SymfonyServerOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return symfonyCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(symfonyCodegen) {{ - symfonyCodegen.setBundleName(SymfonyServerOptionsProvider.BUNDLE_NAME_VALUE); - times = 1; - symfonyCodegen.setModelPackage(SymfonyServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - symfonyCodegen.setApiPackage(SymfonyServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - symfonyCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SymfonyServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - symfonyCodegen.setParameterNamingConvention(SymfonyServerOptionsProvider.VARIABLE_NAMING_CONVENTION_VALUE); - times = 1; - symfonyCodegen.setInvokerPackage(SymfonyServerOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - symfonyCodegen.setPackagePath(SymfonyServerOptionsProvider.PACKAGE_PATH_VALUE); - times = 1; - symfonyCodegen.setSrcBasePath(SymfonyServerOptionsProvider.SRC_BASE_PATH_VALUE); - times = 1; - symfonyCodegen.setComposerVendorName(SymfonyServerOptionsProvider.COMPOSER_VENDOR_NAME_VALUE); - times = 1; - symfonyCodegen.setGitUserId(SymfonyServerOptionsProvider.GIT_USER_ID_VALUE); - times = 1; - symfonyCodegen.setComposerProjectName(SymfonyServerOptionsProvider.COMPOSER_PROJECT_NAME_VALUE); - times = 1; - symfonyCodegen.setGitRepoId(SymfonyServerOptionsProvider.GIT_REPO_ID_VALUE); - times = 1; - symfonyCodegen.setArtifactVersion(SymfonyServerOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java deleted file mode 100644 index 31ad9512ae70..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.qtfivecpp; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.Qt5CPPGenerator; -import org.openapitools.codegen.options.Qt5CPPOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class Qt5CPPOptionsTest extends AbstractOptionsTest { - - @Tested - private Qt5CPPGenerator clientCodegen; - - public Qt5CPPOptionsTest() { - super(new Qt5CPPOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(Qt5CPPOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/ruby/RubyClientCodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/ruby/RubyClientCodegenTest.java deleted file mode 100644 index fb42e20de16e..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/ruby/RubyClientCodegenTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.openapitools.codegen.ruby; - -import org.openapitools.codegen.ClientOpts; -import org.openapitools.codegen.ClientOptInput; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.DefaultGenerator; -import org.openapitools.codegen.languages.RubyClientCodegen; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; - -import org.apache.commons.io.FileUtils; -import org.junit.rules.TemporaryFolder; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.util.List; - -import static org.junit.Assert.fail; -import static org.testng.Assert.*; - -/** - * Tests for RubyClientCodegen-generated templates - */ -public class RubyClientCodegenTest { - - public TemporaryFolder folder = new TemporaryFolder(); - - @BeforeMethod - public void setUp() throws Exception { - folder.create(); - } - - @AfterMethod - public void tearDown() throws Exception { - folder.delete(); - } - - @Test - public void testGenerateRubyClientWithHtmlEntity() throws Exception { - final File output = folder.getRoot(); - - final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/pathWithHtmlEntity.yaml"); - CodegenConfig codegenConfig = new RubyClientCodegen(); - codegenConfig.setOutputDir(output.getAbsolutePath()); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); - boolean apiFileGenerated = false; - for (File file : files) { - if (file.getName().equals("default_api.rb")) { - apiFileGenerated = true; - // Ruby client should set the path unescaped in the api file - assertTrue(FileUtils.readFileToString(file, StandardCharsets.UTF_8).contains("local_var_path = '/foo=bar'")); - } - } - if (!apiFileGenerated) { - fail("Default api file is not generated!"); - } - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/rust/RustClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/rust/RustClientOptionsTest.java deleted file mode 100644 index c65c69c0bc12..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/rust/RustClientOptionsTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.openapitools.codegen.rust; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.RustClientCodegen; -import org.openapitools.codegen.options.RustClientOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class RustClientOptionsTest extends AbstractOptionsTest { - - @Tested - private RustClientCodegen clientCodegen; - - public RustClientOptionsTest() { - super(new RustClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setPackageName(RustClientOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - clientCodegen.setPackageVersion(RustClientOptionsProvider.PACKAGE_VERSION_VALUE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java deleted file mode 100644 index 4bbfb00fa751..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.openapitools.codegen.scala; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.ScalaClientCodegen; -import org.openapitools.codegen.options.ScalaClientOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class ScalaClientOptionsTest extends AbstractOptionsTest { - - @Tested - private ScalaClientCodegen clientCodegen; - - public ScalaClientOptionsTest() { - super(new ScalaClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(ScalaClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(ScalaClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(ScalaClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(ScalaClientOptionsProvider.MODEL_PROPERTY_NAMING); - times = 1; - clientCodegen.setSourceFolder(ScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/scala/ScalaClientRequiredAttributesIntegrationTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/scala/ScalaClientRequiredAttributesIntegrationTest.java deleted file mode 100644 index 66138c36221a..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/scala/ScalaClientRequiredAttributesIntegrationTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.openapitools.codegen.scala; - -import com.google.common.collect.ImmutableMap; -import org.openapitools.codegen.AbstractIntegrationTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.ScalaClientCodegen; -import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -public class ScalaClientRequiredAttributesIntegrationTest extends AbstractIntegrationTest { - - public ScalaClientRequiredAttributesIntegrationTest() { - generateSwaggerMetadata = false; - - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - systemPropertyOverrides = builder - .put(CodegenConstants.APIS, Boolean.TRUE.toString()) - .put(CodegenConstants.MODELS, Boolean.TRUE.toString()) - .put(CodegenConstants.API_DOCS, Boolean.FALSE.toString()) - .put(CodegenConstants.MODEL_DOCS, Boolean.FALSE.toString()) - .put(CodegenConstants.API_TESTS, Boolean.FALSE.toString()) - .put(CodegenConstants.MODEL_TESTS, Boolean.FALSE.toString()) - .put(CodegenConstants.SUPPORTING_FILES, Boolean.FALSE.toString()) - .build(); - } - - @Override - protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { - return new IntegrationTestPathsConfig("scala/client/required-attributes"); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return new ScalaClientCodegen(); - } - - @Override - protected Map configProperties() { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.EXCLUDE_TESTS, Boolean.TRUE.toString()); - return properties; - } - - // TODO: Remove this when super.generatesCorrectDirectoryStructure() is re-enabled. - @Test(description = "Verify Scala client's understanding of 'required' attributes. (disabled awaiting CI fix for integration tests classpath)", enabled = false) - public void test() throws IOException { - this.generatesCorrectDirectoryStructure(); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java deleted file mode 100644 index fb8d7a9b1966..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java +++ /dev/null @@ -1,251 +0,0 @@ -package org.openapitools.codegen.scala; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.ScalaClientCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; - -import com.google.common.collect.Sets; -import org.testng.Assert; -import org.testng.annotations.Test; - -@SuppressWarnings("static-method") -public class ScalaModelTest { - - @Test(description = "convert a simple scala model") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); - final DefaultCodegen codegen = new ScalaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 3); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.getter, "getId"); - Assert.assertEquals(property1.setter, "setId"); - Assert.assertEquals(property1.datatype, "Long"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); - Assert.assertEquals(property1.baseType, "Long"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.getter, "getName"); - Assert.assertEquals(property2.setter, "setName"); - Assert.assertEquals(property2.datatype, "String"); - Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "null"); - Assert.assertEquals(property2.baseType, "String"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.getter, "getCreatedAt"); - Assert.assertEquals(property3.setter, "setCreatedAt"); - Assert.assertEquals(property3.datatype, "Date"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, "null"); - Assert.assertEquals(property3.baseType, "Date"); - Assert.assertFalse(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - } - - @Test(description = "convert a model with list property") - public void listPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id"); - final DefaultCodegen codegen = new ScalaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 2); - - final CodegenProperty property1 = cm.vars.get(1); - Assert.assertEquals(property1.baseName, "urls"); - Assert.assertEquals(property1.getter, "getUrls"); - Assert.assertEquals(property1.setter, "setUrls"); - Assert.assertEquals(property1.datatype, "List[String]"); - Assert.assertEquals(property1.name, "urls"); - Assert.assertEquals(property1.defaultValue, "new ListBuffer[String]() "); - Assert.assertEquals(property1.baseType, "List"); - Assert.assertEquals(property1.containerType, "array"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - } - - @Test(description = "convert a model with a map property") - public void mapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); - final DefaultCodegen codegen = new ScalaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "translations"); - Assert.assertEquals(property1.getter, "getTranslations"); - Assert.assertEquals(property1.setter, "setTranslations"); - Assert.assertEquals(property1.datatype, "Map[String, String]"); - Assert.assertEquals(property1.name, "translations"); - Assert.assertEquals(property1.defaultValue, "new HashMap[String, String]() "); - Assert.assertEquals(property1.baseType, "Map"); - Assert.assertEquals(property1.containerType, "map"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - } - - @Test(description = "convert a model with complex properties") - public void complexPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new ScalaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.getter, "getChildren"); - Assert.assertEquals(property1.setter, "setChildren"); - Assert.assertEquals(property1.datatype, "Children"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.defaultValue, "null"); - Assert.assertEquals(property1.baseType, "Children"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isNotContainer); - } - - @Test(description = "convert a model with complex list property") - public void complexListPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); - final DefaultCodegen codegen = new ScalaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.getter, "getChildren"); - Assert.assertEquals(property1.setter, "setChildren"); - Assert.assertEquals(property1.datatype, "List[Children]"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.defaultValue, "new ListBuffer[Children]() "); - Assert.assertEquals(property1.baseType, "List"); - Assert.assertEquals(property1.containerType, "array"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - } - - @Test(description = "convert a model with complex map property") - public void complexMapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); - final DefaultCodegen codegen = new ScalaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.getter, "getChildren"); - Assert.assertEquals(property1.setter, "setChildren"); - Assert.assertEquals(property1.datatype, "Map[String, Children]"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.defaultValue, "new HashMap[String, Children]() "); - Assert.assertEquals(property1.baseType, "Map"); - Assert.assertEquals(property1.containerType, "map"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - Assert.assertFalse(property1.isNotContainer); - } - - @Test(description = "convert an array model") - public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new ScalaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "an array model"); - Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.parent, "ListBuffer[Children]"); - Assert.assertEquals(cm.imports.size(), 2); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ListBuffer", "Children")).size(), 2); - } - - @Test(description = "convert an map model") - public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new ScalaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a map model"); - Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.parent, "HashMap[String, Children]"); - Assert.assertEquals(cm.imports.size(), 2); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("HashMap", "Children")).size(), 2); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java deleted file mode 100644 index 753f537146ac..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.openapitools.codegen.scalatra; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.ScalatraServerCodegen; -import org.openapitools.codegen.options.ScalatraServerOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class ScalatraServerOptionsTest extends AbstractOptionsTest { - - @Tested - private ScalatraServerCodegen clientCodegen; - - public ScalatraServerOptionsTest() { - super(new ScalatraServerOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(ScalatraServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(ScalatraServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(ScalatraServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setSourceFolder(ScalatraServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java deleted file mode 100644 index 1b4bbb976d34..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.openapitools.codegen.spring; - -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.java.JavaClientOptionsTest; -import org.openapitools.codegen.languages.SpringCodegen; -import org.openapitools.codegen.options.SpringOptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class SpringOptionsTest extends JavaClientOptionsTest { - - @Tested - private SpringCodegen clientCodegen; - - public SpringOptionsTest() { - super(new SpringOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(SpringOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(SpringOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SpringOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(SpringOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(SpringOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(SpringOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(SpringOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(SpringOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(SpringOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(SpringOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setLibrary(SpringOptionsProvider.LIBRARY_VALUE); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(SpringOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setTitle(SpringOptionsProvider.TITLE); - times = 1; - clientCodegen.setConfigPackage(SpringOptionsProvider.CONFIG_PACKAGE_VALUE); - times = 1; - // comment out below to avoid test failures - //clientCodegen.setBasePackage(SpringOptionsProvider.BASE_PACKAGE_VALUE); - //times = 1; - clientCodegen.setInterfaceOnly(Boolean.valueOf(SpringOptionsProvider.INTERFACE_ONLY)); - times = 1; - clientCodegen.setDelegatePattern(Boolean.valueOf(SpringOptionsProvider.DELEGATE_PATTERN)); - times = 1; - clientCodegen.setSingleContentTypes(Boolean.valueOf(SpringOptionsProvider.SINGLE_CONTENT_TYPES)); - times = 1; - // comment out below to avoid test failures - //clientCodegen.setJava8(Boolean.valueOf(SpringOptionsProvider.JAVA_8)); - //times = 1; - clientCodegen.setAsync(Boolean.valueOf(SpringOptionsProvider.ASYNC)); - times = 1; - clientCodegen.setResponseWrapper(SpringOptionsProvider.RESPONSE_WRAPPER); - times = 1; - clientCodegen.setUseTags(Boolean.valueOf(SpringOptionsProvider.USE_TAGS)); - times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(SpringOptionsProvider.USE_BEANVALIDATION)); - times = 1; - clientCodegen.setImplicitHeaders(Boolean.valueOf(SpringOptionsProvider.IMPLICIT_HEADERS)); - times = 1; - clientCodegen.setSwaggerDocketConfig(Boolean.valueOf(SpringOptionsProvider.SWAGGER_DOCKET_CONFIG)); - times = 1; - clientCodegen.setUseOptional( - Boolean.valueOf(SpringOptionsProvider.USE_OPTIONAL)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java deleted file mode 100644 index 45235f157dab..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.staticDocs; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.StaticDocCodegen; -import org.openapitools.codegen.options.StaticDocOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class StaticDocOptionsTest extends AbstractOptionsTest { - - @Tested - private StaticDocCodegen clientCodegen; - - public StaticDocOptionsTest() { - super(new StaticDocOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(StaticDocOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/staticDocs/StaticOperationTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/staticDocs/StaticOperationTest.java deleted file mode 100644 index 968c3411a824..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/staticDocs/StaticOperationTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.openapitools.codegen.staticDocs; - -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.StaticDocCodegen; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; - -import org.testng.Assert; -import org.testng.annotations.Test; - -@SuppressWarnings("static-method") -public class StaticOperationTest { - - @Test(description = "convert a string parameter") - public void stringParameterTest() { - final StringProperty property = new StringProperty(); - final DefaultCodegen codegen = new StaticDocCodegen(); - final CodegenProperty cp = codegen.fromProperty("property", property); - - Assert.assertEquals(cp.baseName, "property"); - Assert.assertEquals(cp.datatype, "String"); - Assert.assertEquals(cp.name, "property"); - Assert.assertEquals(cp.baseType, "string"); - Assert.assertTrue(cp.isNotContainer); - } - - @Test(description = "convert a boolean parameter") - public void booleanParameterTest() { - final BooleanProperty property = new BooleanProperty(); - final DefaultCodegen codegen = new StaticDocCodegen(); - final CodegenProperty cp = codegen.fromProperty("property", property); - - Assert.assertEquals(cp.baseName, "property"); - Assert.assertEquals(cp.datatype, "Boolean"); - Assert.assertEquals(cp.name, "property"); - Assert.assertEquals(cp.baseType, "boolean"); - Assert.assertTrue(cp.isNotContainer); - Assert.assertTrue(cp.isBoolean); - Assert.assertEquals(cp.getter, "getProperty"); - } - - @Test(description = "convert a complex parameter") - public void complexParameterTest() { - final RefProperty property = new RefProperty("Children"); - final DefaultCodegen codegen = new StaticDocCodegen(); - final CodegenProperty cp = codegen.fromProperty("property", property); - - Assert.assertEquals(cp.baseName, "property"); - Assert.assertEquals(cp.complexType, "Children"); - Assert.assertEquals(cp.getter, "getProperty"); - Assert.assertEquals(cp.setter, "setProperty"); - Assert.assertEquals(cp.datatype, "Children"); - Assert.assertEquals(cp.name, "property"); - Assert.assertEquals(cp.defaultValue, "null"); - Assert.assertEquals(cp.baseType, "Children"); - Assert.assertTrue(cp.isNotContainer); - } - - @Test(description = "convert a complex list parameter") - public void listParameterTest() { - final ArrayProperty property = new ArrayProperty().items(new RefProperty("Children")); - final DefaultCodegen codegen = new StaticDocCodegen(); - final CodegenProperty cp = codegen.fromProperty("property", property); - - Assert.assertEquals(cp.baseName, "property"); - Assert.assertEquals(cp.complexType, "Children"); - Assert.assertEquals(cp.getter, "getProperty"); - Assert.assertEquals(cp.setter, "setProperty"); - Assert.assertEquals(cp.datatype, "List"); - Assert.assertEquals(cp.name, "property"); - Assert.assertEquals(cp.baseType, "array"); - Assert.assertEquals(cp.containerType, "array"); - Assert.assertTrue(cp.isContainer); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java deleted file mode 100644 index f5cd17a58dcb..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.statichtml; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.StaticHtmlGenerator; -import org.openapitools.codegen.options.StaticHtmlOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class StaticHtmlOptionsTest extends AbstractOptionsTest { - - @Tested - private StaticHtmlGenerator clientCodegen; - - public StaticHtmlOptionsTest() { - super(new StaticHtmlOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(StaticHtmlOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java deleted file mode 100644 index ada4b141981e..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.openapitools.codegen.statichtml; - -import static org.testng.Assert.assertEquals; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Nullable; - -import org.apache.commons.lang3.StringUtils; -import org.junit.rules.TemporaryFolder; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.google.common.base.Function; -import com.google.common.collect.Lists; - -import org.openapitools.codegen.ClientOptInput; -import org.openapitools.codegen.ClientOpts; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.DefaultGenerator; -import org.openapitools.codegen.languages.StaticHtmlGenerator; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; - -public class StaticHtmlTagsTest { - - public TemporaryFolder folder = new TemporaryFolder(); - - @BeforeMethod - public void setUp() throws Exception { - folder.create(); - } - - @AfterMethod - public void tearDown() throws Exception { - folder.delete(); - } - - @Test - public void testApiTags() throws Exception { - final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/petstore.json"); - - final int maxTagsToTest = 2; // how to flip it randomly from 2 to 1, and shuffle ops? - // if an op has a few tags it will be duplicated here, but it's exactly what we expect in doc - final List expectedOperations = new ArrayList(); - - final String capitalCommatizedTags = pickupFewTagsAndOps(swagger, - maxTagsToTest, expectedOperations); - - final Collection seenOperations = new ArrayList(); - CodegenConfig codegenConfig = new StaticHtmlGenerator(){ // new StaticDocCodegen(){ - public Map postProcessSupportingFileData(Map objs) { - //System.out.println(getOperations(objs)); - final Collection actualOperations = getOperations(objs); - seenOperations.addAll(actualOperations); - assertEquals(actualOperations.size(), expectedOperations.size(), - "Expectig the same size of ops for -Dapis="+capitalCommatizedTags + - " in fact, actual "+actualOperations+" doesn't seem like expecting " - + expectedOperations); - return objs; - } - }; - codegenConfig.setOutputDir(folder.getRoot().getAbsolutePath()); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger) - .config(codegenConfig); - - final String apisBackup = System.setProperty("apis", capitalCommatizedTags); - try { - DefaultGenerator gen = new DefaultGenerator(); - gen.opts(clientOptInput); - gen.generate(); - assertEquals(seenOperations.isEmpty(), false, - "something has been changed in code and now code bypass the mock above..."); - } finally { - if (apisBackup!=null) { - System.setProperty("apis", apisBackup); - }else{ - System.clearProperty("apis"); - } - } - } - - protected String pickupFewTagsAndOps(final Swagger swagger, - final int maxTagsToTest, final Collection expectedOperations) { - Set expectedTags = new HashSet(); - for ( Path path:swagger.getPaths().values() ) { - for ( Operation op : path.getOperations() ) { - for ( String tag : op.getTags() ) { - if (expectedTags.size() < maxTagsToTest) { - expectedTags.add(tag); - expectedOperations.add(op); - } else { - if ( expectedTags.contains(tag) ) { - expectedOperations.add(op); - } - } - } - } - } - - final String capitalCommatizedTags = StringUtils.join( - Lists.transform(Lists.newArrayList(expectedTags), - new Function() { - @Nullable - @Override - public String apply(final String input) { - return StringUtils.capitalize(input); - } - }), ","); - return capitalCommatizedTags; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - protected static Collection getOperations(Map objs) { - final ArrayList rez = new ArrayList(); - final Map apiInfo = (Map)objs.get("apiInfo"); - for(Object apiElem : ((List)apiInfo.get("apis"))){ - Map api = (Map) apiElem; - rez.addAll( (Collection) // what if the same op goes on two tags?? - ((Map)api.get("operations")).get("operation")); - } - return rez; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java deleted file mode 100644 index a2193f3d063a..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.swagger; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.SwaggerGenerator; -import org.openapitools.codegen.options.SwaggerOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class SwaggerOptionsTest extends AbstractOptionsTest { - - @Tested - private SwaggerGenerator clientCodegen; - - public SwaggerOptionsTest() { - super(new SwaggerOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SwaggerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java deleted file mode 100644 index 5dcecb63e09b..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.swaggeryaml; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.SwaggerYamlGenerator; -import org.openapitools.codegen.options.SwaggerYamlOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class SwaggerYamlOptionsTest extends AbstractOptionsTest { - - @Tested - private SwaggerYamlGenerator clientCodegen; - - public SwaggerYamlOptionsTest() { - super(new SwaggerYamlOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SwaggerYamlOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java deleted file mode 100644 index 5b61109f8d33..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.openapitools.codegen.swift; - -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.InlineModelResolver; -import org.openapitools.codegen.languages.SwiftCodegen; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class SwiftCodegenTest { - - SwiftCodegen swiftCodegen = new SwiftCodegen(); - - @Test - public void shouldNotBreakCorrectName() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("EntryName"), "EntryName"); - } - - @Test - public void testSingleWordAllCaps() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("VALUE"), "Value"); - } - - @Test - public void testSingleWordLowercase() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("value"), "Value"); - } - - @Test - public void testCapitalsWithUnderscore() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY_NAME"), "EntryName"); - } - - @Test - public void testCapitalsWithDash() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY-NAME"), "EntryName"); - } - - @Test - public void testCapitalsWithSpace() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY NAME"), "EntryName"); - } - - @Test - public void testLowercaseWithUnderscore() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("entry_name"), "EntryName"); - } - - @Test - public void testSlash() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("application/x-tar"), "ApplicationXTar"); - } - - @Test(description = "returns NSData when response format is binary") - public void binaryDataTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); - final DefaultCodegen codegen = new SwiftCodegen(); - final String path = "/tests/binaryResponse"; - final Operation p = model.getPaths().get(path).getPost(); - final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); - - Assert.assertEquals(op.returnType, "NSData"); - Assert.assertEquals(op.bodyParam.dataType, "NSData"); - Assert.assertTrue(op.bodyParam.isBinary); - Assert.assertTrue(op.responses.get(0).isBinary); - } - - @Test(description = "returns ISOFullDate when response format is date") - public void dateTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/datePropertyTest.json"); - final DefaultCodegen codegen = new SwiftCodegen(); - final String path = "/tests/dateResponse"; - final Operation p = model.getPaths().get(path).getPost(); - final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); - - Assert.assertEquals(op.returnType, "ISOFullDate"); - Assert.assertEquals(op.bodyParam.dataType, "ISOFullDate"); - } - - @Test - public void testDefaultPodAuthors() throws Exception { - // Given - - // When - swiftCodegen.processOpts(); - - // Then - final String podAuthors = (String) swiftCodegen.additionalProperties().get(SwiftCodegen.POD_AUTHORS); - Assert.assertEquals(podAuthors, SwiftCodegen.DEFAULT_POD_AUTHORS); - } - - @Test - public void testPodAuthors() throws Exception { - // Given - final String swaggerDevs = "Swagger Devs"; - swiftCodegen.additionalProperties().put(SwiftCodegen.POD_AUTHORS, swaggerDevs); - - // When - swiftCodegen.processOpts(); - - // Then - final String podAuthors = (String) swiftCodegen.additionalProperties().get(SwiftCodegen.POD_AUTHORS); - Assert.assertEquals(podAuthors, swaggerDevs); - } - -} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java deleted file mode 100644 index 9339cd2c1f23..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.openapitools.codegen.swift; - -import org.openapitools.codegen.*; -import org.openapitools.codegen.languages.SwiftCodegen; -import io.swagger.models.*; -import io.swagger.models.properties.*; - -import org.testng.Assert; -import org.testng.annotations.Test; - -@SuppressWarnings("static-method") -public class SwiftModelTest { - - @Test(description = "convert a simple java model") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .property("binary", new BinaryProperty()) - .property("byte", new ByteArrayProperty()) - .property("uuid", new UUIDProperty()) - .property("dateOfBirth", new DateProperty()) - .required("id") - .required("name") - .discriminator("test"); - final DefaultCodegen codegen = new SwiftCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 7); - Assert.assertEquals(cm.discriminator,"test"); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "Int64"); - Assert.assertEquals(property1.name, "id"); - Assert.assertNull(property1.defaultValue); - Assert.assertEquals(property1.baseType, "Int64"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isPrimitiveType); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.datatype, "String"); - Assert.assertEquals(property2.name, "name"); - Assert.assertNull(property2.defaultValue); - Assert.assertEquals(property2.baseType, "String"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isPrimitiveType); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.datatype, "NSDate"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertNull(property3.defaultValue); - Assert.assertEquals(property3.baseType, "NSDate"); - Assert.assertTrue(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - - final CodegenProperty property4 = cm.vars.get(3); - Assert.assertEquals(property4.baseName, "binary"); - Assert.assertEquals(property4.datatype, "NSData"); - Assert.assertEquals(property4.name, "binary"); - Assert.assertNull(property4.defaultValue); - Assert.assertEquals(property4.baseType, "NSData"); - Assert.assertTrue(property4.hasMore); - Assert.assertFalse(property4.required); - Assert.assertTrue(property4.isNotContainer); - - final CodegenProperty property5 = cm.vars.get(4); - Assert.assertEquals(property5.baseName, "byte"); - Assert.assertEquals(property5.datatype, "NSData"); - Assert.assertEquals(property5.name, "byte"); - Assert.assertNull(property5.defaultValue); - Assert.assertEquals(property5.baseType, "NSData"); - Assert.assertTrue(property5.hasMore); - Assert.assertFalse(property5.required); - Assert.assertTrue(property5.isNotContainer); - - final CodegenProperty property6 = cm.vars.get(5); - Assert.assertEquals(property6.baseName, "uuid"); - Assert.assertEquals(property6.datatype, "NSUUID"); - Assert.assertEquals(property6.name, "uuid"); - Assert.assertNull(property6.defaultValue); - Assert.assertEquals(property6.baseType, "NSUUID"); - Assert.assertTrue(property6.hasMore); - Assert.assertFalse(property6.required); - Assert.assertTrue(property6.isNotContainer); - - final CodegenProperty property7 = cm.vars.get(6); - Assert.assertEquals(property7.baseName, "dateOfBirth"); - Assert.assertEquals(property7.datatype, "ISOFullDate"); - Assert.assertEquals(property7.name, "dateOfBirth"); - Assert.assertNull(property7.defaultValue); - Assert.assertEquals(property7.baseType, "ISOFullDate"); - Assert.assertFalse(property7.hasMore); - Assert.assertFalse(property7.required); - Assert.assertTrue(property7.isNotContainer); - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java deleted file mode 100644 index 83d03b42ea7d..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.openapitools.codegen.swift; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.SwiftCodegen; -import org.openapitools.codegen.options.SwiftOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class SwiftOptionsTest extends AbstractOptionsTest { - - @Tested - private SwiftCodegen clientCodegen; - - public SwiftOptionsTest() { - super(new SwiftOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SwiftOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setProjectName(SwiftOptionsProvider.PROJECT_NAME_VALUE); - times = 1; - clientCodegen.setResponseAs(SwiftOptionsProvider.RESPONSE_AS_VALUE.split(",")); - times = 1; - clientCodegen.setUnwrapRequired(Boolean.valueOf(SwiftOptionsProvider.UNWRAP_REQUIRED_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java deleted file mode 100644 index 4cd27dbd84f5..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package org.openapitools.codegen.swift3; - -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.Swift3Codegen; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class Swift3CodegenTest { - - Swift3Codegen swiftCodegen = new Swift3Codegen(); - - @Test - public void testCapitalizedReservedWord() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("AS", null), "_as"); - } - - @Test - public void testReservedWord() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("Public", null), "_public"); - } - - @Test - public void shouldNotBreakNonReservedWord() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("Error", null), "error"); - } - - @Test - public void shouldNotBreakCorrectName() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("EntryName", null), "entryName"); - } - - @Test - public void testSingleWordAllCaps() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("VALUE", null), "value"); - } - - @Test - public void testSingleWordLowercase() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("value", null), "value"); - } - - @Test - public void testCapitalsWithUnderscore() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY_NAME", null), "entryName"); - } - - @Test - public void testCapitalsWithDash() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY-NAME", null), "entryName"); - } - - @Test - public void testCapitalsWithSpace() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY NAME", null), "entryName"); - } - - @Test - public void testLowercaseWithUnderscore() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("entry_name", null), "entryName"); - } - - @Test - public void testStartingWithNumber() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("123EntryName", null), "_123entryName"); - Assert.assertEquals(swiftCodegen.toEnumVarName("123Entry_name", null), "_123entryName"); - Assert.assertEquals(swiftCodegen.toEnumVarName("123EntryName123", null), "_123entryName123"); - } - - @Test(description = "returns NSData when response format is binary") - public void binaryDataTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); - final DefaultCodegen codegen = new Swift3Codegen(); - final String path = "/tests/binaryResponse"; - final Operation p = model.getPaths().get(path).getPost(); - final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); - - Assert.assertEquals(op.returnType, "Data"); - Assert.assertEquals(op.bodyParam.dataType, "Data"); - Assert.assertTrue(op.bodyParam.isBinary); - Assert.assertTrue(op.responses.get(0).isBinary); - } - - @Test(description = "returns ISOFullDate when response format is date") - public void dateTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/datePropertyTest.json"); - final DefaultCodegen codegen = new Swift3Codegen(); - final String path = "/tests/dateResponse"; - final Operation p = model.getPaths().get(path).getPost(); - final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); - - Assert.assertEquals(op.returnType, "ISOFullDate"); - Assert.assertEquals(op.bodyParam.dataType, "ISOFullDate"); - } - - @Test - public void testDefaultPodAuthors() throws Exception { - // Given - - // When - swiftCodegen.processOpts(); - - // Then - final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift3Codegen.POD_AUTHORS); - Assert.assertEquals(podAuthors, Swift3Codegen.DEFAULT_POD_AUTHORS); - } - - @Test - public void testPodAuthors() throws Exception { - // Given - final String swaggerDevs = "Swagger Devs"; - swiftCodegen.additionalProperties().put(Swift3Codegen.POD_AUTHORS, swaggerDevs); - - // When - swiftCodegen.processOpts(); - - // Then - final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift3Codegen.POD_AUTHORS); - Assert.assertEquals(podAuthors, swaggerDevs); - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift3/Swift3ModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/swift3/Swift3ModelTest.java deleted file mode 100644 index 7912acaf25bb..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift3/Swift3ModelTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.openapitools.codegen.swift3; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.Swift3Codegen; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.*; -import org.testng.Assert; -import org.testng.annotations.Test; - -@SuppressWarnings("static-method") -public class Swift3ModelTest { - - @Test(description = "convert a simple java model") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .property("binary", new BinaryProperty()) - .property("byte", new ByteArrayProperty()) - .property("uuid", new UUIDProperty()) - .property("dateOfBirth", new DateProperty()) - .required("id") - .required("name") - .discriminator("test"); - final DefaultCodegen codegen = new Swift3Codegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 7); - Assert.assertEquals(cm.discriminator,"test"); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "Int64"); - Assert.assertEquals(property1.name, "id"); - Assert.assertNull(property1.defaultValue); - Assert.assertEquals(property1.baseType, "Int64"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isPrimitiveType); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.datatype, "String"); - Assert.assertEquals(property2.name, "name"); - Assert.assertNull(property2.defaultValue); - Assert.assertEquals(property2.baseType, "String"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isPrimitiveType); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.datatype, "Date"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertNull(property3.defaultValue); - Assert.assertEquals(property3.baseType, "Date"); - Assert.assertTrue(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - - final CodegenProperty property4 = cm.vars.get(3); - Assert.assertEquals(property4.baseName, "binary"); - Assert.assertEquals(property4.datatype, "Data"); - Assert.assertEquals(property4.name, "binary"); - Assert.assertNull(property4.defaultValue); - Assert.assertEquals(property4.baseType, "Data"); - Assert.assertTrue(property4.hasMore); - Assert.assertFalse(property4.required); - Assert.assertTrue(property4.isNotContainer); - - final CodegenProperty property5 = cm.vars.get(4); - Assert.assertEquals(property5.baseName, "byte"); - Assert.assertEquals(property5.datatype, "Data"); - Assert.assertEquals(property5.name, "byte"); - Assert.assertNull(property5.defaultValue); - Assert.assertEquals(property5.baseType, "Data"); - Assert.assertTrue(property5.hasMore); - Assert.assertFalse(property5.required); - Assert.assertTrue(property5.isNotContainer); - - final CodegenProperty property6 = cm.vars.get(5); - Assert.assertEquals(property6.baseName, "uuid"); - Assert.assertEquals(property6.datatype, "UUID"); - Assert.assertEquals(property6.name, "uuid"); - Assert.assertNull(property6.defaultValue); - Assert.assertEquals(property6.baseType, "UUID"); - Assert.assertTrue(property6.hasMore); - Assert.assertFalse(property6.required); - Assert.assertTrue(property6.isNotContainer); - - final CodegenProperty property7 = cm.vars.get(6); - Assert.assertEquals(property7.baseName, "dateOfBirth"); - Assert.assertEquals(property7.datatype, "ISOFullDate"); - Assert.assertEquals(property7.name, "dateOfBirth"); - Assert.assertNull(property7.defaultValue); - Assert.assertEquals(property7.baseType, "ISOFullDate"); - Assert.assertFalse(property7.hasMore); - Assert.assertFalse(property7.required); - Assert.assertTrue(property7.isNotContainer); - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift3/Swift3OptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/swift3/Swift3OptionsTest.java deleted file mode 100644 index 4d21f51412a6..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift3/Swift3OptionsTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.openapitools.codegen.swift3; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.Swift3Codegen; -import org.openapitools.codegen.options.Swift3OptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class Swift3OptionsTest extends AbstractOptionsTest { - - @Tested - private Swift3Codegen clientCodegen; - - public Swift3OptionsTest() { - super(new Swift3OptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(Swift3OptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setProjectName(Swift3OptionsProvider.PROJECT_NAME_VALUE); - times = 1; - clientCodegen.setResponseAs(Swift3OptionsProvider.RESPONSE_AS_VALUE.split(",")); - times = 1; - clientCodegen.setUnwrapRequired(Boolean.valueOf(Swift3OptionsProvider.UNWRAP_REQUIRED_VALUE)); - times = 1; - clientCodegen.setObjcCompatible(Boolean.valueOf(Swift3OptionsProvider.OBJC_COMPATIBLE_VALUE)); - times = 1; - clientCodegen.setLenientTypeCast(Boolean.valueOf(Swift3OptionsProvider.LENIENT_TYPE_CAST_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift4/Swift4CodegenTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/swift4/Swift4CodegenTest.java deleted file mode 100644 index f3b1c24e4bb8..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift4/Swift4CodegenTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package org.openapitools.codegen.swift4; - -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.Swift4Codegen; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class Swift4CodegenTest { - - Swift4Codegen swiftCodegen = new Swift4Codegen(); - - @Test - public void testCapitalizedReservedWord() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("AS", null), "_as"); - } - - @Test - public void testReservedWord() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("Public", null), "_public"); - } - - @Test - public void shouldNotBreakNonReservedWord() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("Error", null), "error"); - } - - @Test - public void shouldNotBreakCorrectName() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("EntryName", null), "entryName"); - } - - @Test - public void testSingleWordAllCaps() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("VALUE", null), "value"); - } - - @Test - public void testSingleWordLowercase() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("value", null), "value"); - } - - @Test - public void testCapitalsWithUnderscore() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY_NAME", null), "entryName"); - } - - @Test - public void testCapitalsWithDash() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY-NAME", null), "entryName"); - } - - @Test - public void testCapitalsWithSpace() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY NAME", null), "entryName"); - } - - @Test - public void testLowercaseWithUnderscore() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("entry_name", null), "entryName"); - } - - @Test - public void testStartingWithNumber() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("123EntryName", null), "_123entryName"); - Assert.assertEquals(swiftCodegen.toEnumVarName("123Entry_name", null), "_123entryName"); - Assert.assertEquals(swiftCodegen.toEnumVarName("123EntryName123", null), "_123entryName123"); - } - - @Test(description = "returns Data when response format is binary") - public void binaryDataTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); - final DefaultCodegen codegen = new Swift4Codegen(); - final String path = "/tests/binaryResponse"; - final Operation p = model.getPaths().get(path).getPost(); - final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); - - Assert.assertEquals(op.returnType, "Data"); - Assert.assertEquals(op.bodyParam.dataType, "Data"); - Assert.assertTrue(op.bodyParam.isBinary); - Assert.assertTrue(op.responses.get(0).isBinary); - } - - @Test(description = "returns Date when response format is date") - public void dateTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/datePropertyTest.json"); - final DefaultCodegen codegen = new Swift4Codegen(); - final String path = "/tests/dateResponse"; - final Operation p = model.getPaths().get(path).getPost(); - final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); - - Assert.assertEquals(op.returnType, "Date"); - Assert.assertEquals(op.bodyParam.dataType, "Date"); - } - - @Test - public void testDefaultPodAuthors() throws Exception { - // Given - - // When - swiftCodegen.processOpts(); - - // Then - final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift4Codegen.POD_AUTHORS); - Assert.assertEquals(podAuthors, Swift4Codegen.DEFAULT_POD_AUTHORS); - } - - @Test - public void testPodAuthors() throws Exception { - // Given - final String swaggerDevs = "Swagger Devs"; - swiftCodegen.additionalProperties().put(Swift4Codegen.POD_AUTHORS, swaggerDevs); - - // When - swiftCodegen.processOpts(); - - // Then - final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift4Codegen.POD_AUTHORS); - Assert.assertEquals(podAuthors, swaggerDevs); - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift4/Swift4ModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/swift4/Swift4ModelTest.java deleted file mode 100644 index 7e808952d374..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift4/Swift4ModelTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.openapitools.codegen.swift4; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.Swift4Codegen; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.*; -import org.testng.Assert; -import org.testng.annotations.Test; - -@SuppressWarnings("static-method") -public class Swift4ModelTest { - - @Test(description = "convert a simple java model") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .property("binary", new BinaryProperty()) - .property("byte", new ByteArrayProperty()) - .property("uuid", new UUIDProperty()) - .property("dateOfBirth", new DateProperty()) - .required("id") - .required("name") - .discriminator("test"); - final DefaultCodegen codegen = new Swift4Codegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 7); - Assert.assertEquals(cm.discriminator,"test"); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "Int64"); - Assert.assertEquals(property1.name, "_id"); - Assert.assertNull(property1.defaultValue); - Assert.assertEquals(property1.baseType, "Int64"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isPrimitiveType); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.datatype, "String"); - Assert.assertEquals(property2.name, "name"); - Assert.assertNull(property2.defaultValue); - Assert.assertEquals(property2.baseType, "String"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isPrimitiveType); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.datatype, "Date"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertNull(property3.defaultValue); - Assert.assertEquals(property3.baseType, "Date"); - Assert.assertTrue(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - - final CodegenProperty property4 = cm.vars.get(3); - Assert.assertEquals(property4.baseName, "binary"); - Assert.assertEquals(property4.datatype, "Data"); - Assert.assertEquals(property4.name, "binary"); - Assert.assertNull(property4.defaultValue); - Assert.assertEquals(property4.baseType, "Data"); - Assert.assertTrue(property4.hasMore); - Assert.assertFalse(property4.required); - Assert.assertTrue(property4.isNotContainer); - - final CodegenProperty property5 = cm.vars.get(4); - Assert.assertEquals(property5.baseName, "byte"); - Assert.assertEquals(property5.datatype, "Data"); - Assert.assertEquals(property5.name, "byte"); - Assert.assertNull(property5.defaultValue); - Assert.assertEquals(property5.baseType, "Data"); - Assert.assertTrue(property5.hasMore); - Assert.assertFalse(property5.required); - Assert.assertTrue(property5.isNotContainer); - - final CodegenProperty property6 = cm.vars.get(5); - Assert.assertEquals(property6.baseName, "uuid"); - Assert.assertEquals(property6.datatype, "UUID"); - Assert.assertEquals(property6.name, "uuid"); - Assert.assertNull(property6.defaultValue); - Assert.assertEquals(property6.baseType, "UUID"); - Assert.assertTrue(property6.hasMore); - Assert.assertFalse(property6.required); - Assert.assertTrue(property6.isNotContainer); - - final CodegenProperty property7 = cm.vars.get(6); - Assert.assertEquals(property7.baseName, "dateOfBirth"); - Assert.assertEquals(property7.datatype, "Date"); - Assert.assertEquals(property7.name, "dateOfBirth"); - Assert.assertNull(property7.defaultValue); - Assert.assertEquals(property7.baseType, "Date"); - Assert.assertFalse(property7.hasMore); - Assert.assertFalse(property7.required); - Assert.assertTrue(property7.isNotContainer); - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift4/Swift4OptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/swift4/Swift4OptionsTest.java deleted file mode 100644 index 234947ded9b6..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/swift4/Swift4OptionsTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.openapitools.codegen.swift4; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.Swift4Codegen; -import org.openapitools.codegen.options.Swift4OptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class Swift4OptionsTest extends AbstractOptionsTest { - - @Tested - private Swift4Codegen clientCodegen; - - public Swift4OptionsTest() { - super(new Swift4OptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(Swift4OptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setProjectName(Swift4OptionsProvider.PROJECT_NAME_VALUE); - times = 1; - clientCodegen.setResponseAs(Swift4OptionsProvider.RESPONSE_AS_VALUE.split(",")); - times = 1; - clientCodegen.setUnwrapRequired(Boolean.valueOf(Swift4OptionsProvider.UNWRAP_REQUIRED_VALUE)); - times = 1; - clientCodegen.setObjcCompatible(Boolean.valueOf(Swift4OptionsProvider.OBJC_COMPATIBLE_VALUE)); - times = 1; - clientCodegen.setLenientTypeCast(Boolean.valueOf(Swift4OptionsProvider.LENIENT_TYPE_CAST_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/testutils/AssertFile.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/testutils/AssertFile.java deleted file mode 100644 index ac9ac6ae32ed..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/testutils/AssertFile.java +++ /dev/null @@ -1,143 +0,0 @@ -package org.openapitools.codegen.testutils; - -import org.testng.Assert; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.FileVisitResult; -import java.nio.file.FileVisitor; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.Arrays; -import java.util.List; - -import difflib.Delta; -import difflib.DiffUtils; -import difflib.Patch; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -/** - * Assertion for recursively testing directories. - * - * @author andreas - */ -public class AssertFile { - - private AssertFile() { - throw new RuntimeException("This class should not be instantiated"); - } - - /** - * Asserts that two directories are recursively equal. If they are not, an {@link AssertionError} is thrown with the - * given message.
- * There will be a textual comparison of all files under expected with all files under actual. File attributes will - * not be considered.
- * Missing or additional files are considered an error.
- * - * @param expected Path expected directory - * @param actual Path actual directory - */ - public static void assertPathEqualsRecursively(final Path expected, final Path actual) { - Assert.assertNotNull(expected); - Assert.assertNotNull(actual); - final Path absoluteExpected = expected.toAbsolutePath(); - final Path absoluteActual = actual.toAbsolutePath(); - try { - Files.walkFileTree(expected, new FileVisitor() { - - @Override - public FileVisitResult preVisitDirectory(Path expectedDir, BasicFileAttributes attrs) throws IOException { - Path relativeExpectedDir = absoluteExpected.relativize(expectedDir.toAbsolutePath()); - Path actualDir = absoluteActual.resolve(relativeExpectedDir); - - if (!Files.exists(actualDir)) { - fail(String.format("Directory '%s' is missing.", actualDir)); - } - - String[] expected = expectedDir.toFile().list(); - String[] actual = actualDir.toFile().list(); - - if (expected != null) { - Arrays.sort(expected); - } - if (actual != null) { - Arrays.sort(actual); - } - - assertEquals(expected, - actual, - String.format("Directory content of '%s' and '%s' differ.", expectedDir, actualDir)); - - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path expectedFile, BasicFileAttributes attrs) throws IOException { - Path relativeExpectedFile = absoluteExpected.relativize(expectedFile.toAbsolutePath()); - Path actualFile = absoluteActual.resolve(relativeExpectedFile); - - if (!Files.exists(actualFile)) { - fail(String.format("File '%s' is missing.", actualFile)); - } - - assertFilesAreEqual(expectedFile, actualFile); - - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { - fail(exc.getMessage()); - return FileVisitResult.TERMINATE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - return FileVisitResult.CONTINUE; - } - - }); - } catch (IOException e) { - fail(e.getMessage(), e); - } - } - - - public static void assertFilesAreEqual(final Path expected, final Path actual) { - - if(!Files.isRegularFile(expected)) { - fail("expected: '%s' is not a readable file"); - } - - if(!Files.isRegularFile(actual)) { - fail("actual: '%s' is not a readable file"); - } - - try { - List expectedLines = Files.readAllLines(expected, Charset.defaultCharset()); - List actualLines = Files.readAllLines(actual, Charset.defaultCharset()); - Patch diff = DiffUtils.diff(expectedLines, actualLines); - List deltas = diff.getDeltas(); - if(!deltas.isEmpty()) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("files diff:\n"); - stringBuilder.append("\tfile: '").append(expected.toAbsolutePath().toString()).append("' \n"); - stringBuilder.append("\tfile: '").append(actual.toAbsolutePath().toString()).append("' \n"); - stringBuilder.append("\tdiffs:\n"); - - for (Delta delta: deltas) { - stringBuilder.append(delta.toString()).append("\n"); - } - - fail(stringBuilder.toString()); - } - - } catch (IOException e) { - fail(e.getMessage(), e); - } - } -} - diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java deleted file mode 100644 index 61d3166245e1..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openapitools.codegen.testutils; - -import java.nio.file.Path; -import java.nio.file.Paths; - -public class IntegrationTestPathsConfig { - private static final Path INTEGRATION_TEST_PATH = Paths.get("target/test-classes/integrationtests").toAbsolutePath(); - private final Path outputPath; - private final Path specPath; - private final Path expectedPath; - private final Path ignoreFilePath; - - public IntegrationTestPathsConfig(String location) { - this(location + "-spec.json", location + "-result", location + "-expected", location + ".ignore"); - } - - public IntegrationTestPathsConfig(String specLocation, String outputLocation, String expectedLocation, String ignoreFileLocation) { - outputPath = INTEGRATION_TEST_PATH.resolve(outputLocation); - expectedPath = INTEGRATION_TEST_PATH.resolve(expectedLocation); - specPath = INTEGRATION_TEST_PATH.resolve(specLocation); - ignoreFilePath = INTEGRATION_TEST_PATH.resolve(ignoreFileLocation); - } - - public Path getOutputPath() { - return outputPath; - } - - public Path getSpecPath() { - return specPath; - } - - public Path getExpectedPath() { - return expectedPath; - } - - public Path getIgnoreFilePath() { return ignoreFilePath; } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java deleted file mode 100644 index 517c47cca777..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.tizen; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.TizenClientCodegen; -import org.openapitools.codegen.options.TizenClientOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class TizenClientOptionsTest extends AbstractOptionsTest { - - @Tested - private TizenClientCodegen clientCodegen; - - public TizenClientOptionsTest() { - super(new TizenClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TizenClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/aurelia/TypeScriptAureliaClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/aurelia/TypeScriptAureliaClientOptionsTest.java deleted file mode 100644 index 2a5b0c6ac28e..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/aurelia/TypeScriptAureliaClientOptionsTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.openapitools.codegen.typescript.aurelia; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.TypeScriptAureliaClientCodegen; -import org.openapitools.codegen.options.TypeScriptAureliaClientOptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class TypeScriptAureliaClientOptionsTest extends AbstractOptionsTest { - - @Tested - private TypeScriptAureliaClientCodegen clientCodegen; - - public TypeScriptAureliaClientOptionsTest() { - super(new TypeScriptAureliaClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptAureliaClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(TypeScriptAureliaClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); - times = 1; - clientCodegen.setSupportsES6(TypeScriptAureliaClientOptionsProvider.SUPPORTS_ES6_VALUE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java deleted file mode 100644 index 1b938104fe58..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.openapitools.codegen.typescript.fetch; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen; -import org.openapitools.codegen.options.TypeScriptFetchClientOptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class TypeScriptFetchClientOptionsTest extends AbstractOptionsTest { - - @Tested - private TypeScriptFetchClientCodegen clientCodegen; - - public TypeScriptFetchClientOptionsTest() { - super(new TypeScriptFetchClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(TypeScriptFetchClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); - times = 1; - clientCodegen.setSupportsES6(TypeScriptFetchClientOptionsProvider.SUPPORTS_ES6_VALUE); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java deleted file mode 100644 index ddd5a022bb65..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java +++ /dev/null @@ -1,260 +0,0 @@ -package org.openapitools.codegen.typescript.fetch; - -import com.google.common.collect.Sets; - -import io.swagger.models.properties.*; -import org.testng.Assert; -import org.testng.annotations.Test; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; - -import java.util.HashMap; -import java.util.Arrays; - -@SuppressWarnings("static-method") -public class TypeScriptFetchModelTest { - - @Test(description = "convert a simple TypeScript Angular model") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .property("birthDate", new DateProperty()) - .required("id") - .required("name"); - final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 4); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "number"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "undefined"); - Assert.assertEquals(property1.baseType, "number"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.datatype, "string"); - Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "undefined"); - Assert.assertEquals(property2.baseType, "string"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.complexType, null); - Assert.assertEquals(property3.datatype, "Date"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, "undefined"); - Assert.assertTrue(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - - final CodegenProperty property4 = cm.vars.get(3); - Assert.assertEquals(property4.baseName, "birthDate"); - Assert.assertEquals(property4.complexType, null); - Assert.assertEquals(property4.datatype, "string"); - Assert.assertEquals(property4.name, "birthDate"); - Assert.assertEquals(property4.defaultValue, "undefined"); - Assert.assertFalse(property4.hasMore); - Assert.assertFalse(property4.required); - Assert.assertTrue(property4.isNotContainer); - } - - @Test(description = "convert a model with list property") - public void listPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty().items(new StringProperty())) - .required("id"); - final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 2); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "number"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "undefined"); - Assert.assertEquals(property1.baseType, "number"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "urls"); - Assert.assertEquals(property2.datatype, "Array"); - Assert.assertEquals(property2.name, "urls"); - Assert.assertEquals(property2.baseType, "Array"); - Assert.assertFalse(property2.hasMore); - Assert.assertFalse(property2.required); - Assert.assertTrue(property2.isContainer); - } - - @Test(description = "convert a model with complex property") - public void complexPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.datatype, "Children"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.defaultValue, "undefined"); - Assert.assertEquals(property1.baseType, "Children"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isNotContainer); - } - - @Test(description = "convert a model with complex list property") - public void complexListPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); - final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.datatype, "Array"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.baseType, "Array"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - } - - @Test(description = "convert an array model") - public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "an array model"); - Assert.assertEquals(cm.vars.size(), 0); - } - - @Test(description = "convert a map model") - public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a map model"); - Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - } - - @Test(description = "test enum array model") - public void enumArrayMdoelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); - final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); - final Model definition = model.getDefinitions().get("EnumArrays"); - - Property property = definition.getProperties().get("array_enum"); - CodegenProperty prope = codegen.fromProperty("array_enum", property); - codegen.updateCodegenPropertyEnum(prope); - Assert.assertEquals(prope.datatypeWithEnum, "Array"); - Assert.assertEquals(prope.enumName, "ArrayEnumEnum"); - Assert.assertTrue(prope.isEnum); - Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList("fish", "crab")); - - HashMap fish= new HashMap(); - fish.put("name", "Fish"); - fish.put("value", "'fish'"); - HashMap crab= new HashMap(); - crab.put("name", "Crab"); - crab.put("value", "'crab'"); - Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); - - // assert inner items - Assert.assertEquals(prope.datatypeWithEnum, "Array"); - Assert.assertEquals(prope.enumName, "ArrayEnumEnum"); - Assert.assertTrue(prope.items.isEnum); - Assert.assertEquals(prope.items.allowableValues.get("values"), Arrays.asList("fish", "crab")); - Assert.assertEquals(prope.items.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); - - //IMPORTANT: these are not final enum values, which may be further updated - //by postProcessModels - - } - - @Test(description = "test enum model for values (numeric, string, etc)") - public void enumMdoelValueTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); - final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); - final Model definition = model.getDefinitions().get("Enum_Test"); - - Property property = definition.getProperties().get("enum_integer"); - CodegenProperty prope = codegen.fromProperty("enum_integer", property); - codegen.updateCodegenPropertyEnum(prope); - Assert.assertEquals(prope.datatypeWithEnum, "EnumIntegerEnum"); - Assert.assertEquals(prope.enumName, "EnumIntegerEnum"); - Assert.assertTrue(prope.isEnum); - Assert.assertFalse(prope.isContainer); - Assert.assertNull(prope.items); - Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList(1, -1)); - - HashMap one = new HashMap(); - one.put("name", "NUMBER_1"); - one.put("value", "1"); - HashMap minusOne = new HashMap(); - minusOne.put("name", "NUMBER_MINUS_1"); - minusOne.put("value", "-1"); - Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(one, minusOne)); - - //IMPORTANT: these are not final enum values, which may be further updated - //by postProcessModels - - } - - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java deleted file mode 100644 index 2c4aa7d8e80e..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.openapitools.codegen.typescript.typescriptangular; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; -import org.openapitools.codegen.options.TypeScriptAngularClientOptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class TypeScriptAngularClientOptionsTest extends AbstractOptionsTest { - - @Tested - private TypeScriptAngularClientCodegen clientCodegen; - - public TypeScriptAngularClientOptionsTest() { - super(new TypeScriptAngularClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(TypeScriptAngularClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); - times = 1; - clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.SUPPORTS_ES6_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypescriptAngularAdditionalPropertiesIntegrationTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypescriptAngularAdditionalPropertiesIntegrationTest.java deleted file mode 100644 index 0a63c2f4829d..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypescriptAngularAdditionalPropertiesIntegrationTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.openapitools.codegen.typescript.typescriptangular; - -import java.util.HashMap; -import java.util.Map; - -import org.openapitools.codegen.AbstractIntegrationTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; -import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; - -public class TypescriptAngularAdditionalPropertiesIntegrationTest extends AbstractIntegrationTest { - - @Override - protected CodegenConfig getCodegenConfig() { - return new TypeScriptAngularClientCodegen(); - } - - @Override - protected Map configProperties() { - Map properties = new HashMap<>(); - properties.put("npmName", "additionalPropertiesTest"); - properties.put("npmVersion", "1.0.2"); - properties.put("snapshot", "false"); - - return properties; - } - - @Override - protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { - return new IntegrationTestPathsConfig("typescript/additional-properties"); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangularjs/TypeScriptAngularJsClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangularjs/TypeScriptAngularJsClientOptionsTest.java deleted file mode 100644 index 24038016420f..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangularjs/TypeScriptAngularJsClientOptionsTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openapitools.codegen.typescript.typescriptangularjs; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.TypeScriptAngularJsClientCodegen; -import org.openapitools.codegen.options.TypeScriptAngularJsClientOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class TypeScriptAngularJsClientOptionsTest extends AbstractOptionsTest { - - @Tested - private TypeScriptAngularJsClientCodegen clientCodegen; - - public TypeScriptAngularJsClientOptionsTest() { - super(new TypeScriptAngularJsClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptAngularJsClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(TypeScriptAngularJsClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); - times = 1; - clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptAngularJsClientOptionsProvider.SUPPORTS_ES6_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangularjs/TypeScriptAngularJsModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangularjs/TypeScriptAngularJsModelTest.java deleted file mode 100644 index 0888d0e3c708..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangularjs/TypeScriptAngularJsModelTest.java +++ /dev/null @@ -1,189 +0,0 @@ -package org.openapitools.codegen.typescript.typescriptangularjs; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.TypeScriptAngularJsClientCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.*; - -import com.google.common.collect.Sets; -import org.testng.Assert; -import org.testng.annotations.Test; - -@SuppressWarnings("static-method") -public class TypeScriptAngularJsModelTest { - - @Test(description = "convert a simple TypeScript Angular model") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .property("birthDate", new DateProperty()) - .required("id") - .required("name"); - final DefaultCodegen codegen = new TypeScriptAngularJsClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 4); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "number"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "undefined"); - Assert.assertEquals(property1.baseType, "number"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.datatype, "string"); - Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "undefined"); - Assert.assertEquals(property2.baseType, "string"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.complexType, null); - Assert.assertEquals(property3.datatype, "Date"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, "undefined"); - Assert.assertTrue(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - - final CodegenProperty property4 = cm.vars.get(3); - Assert.assertEquals(property4.baseName, "birthDate"); - Assert.assertEquals(property4.complexType, null); - Assert.assertEquals(property4.datatype, "string"); - Assert.assertEquals(property4.name, "birthDate"); - Assert.assertEquals(property4.defaultValue, "undefined"); - Assert.assertFalse(property4.hasMore); - Assert.assertFalse(property4.required); - Assert.assertTrue(property4.isNotContainer); - } - - @Test(description = "convert a model with list property") - public void listPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty().items(new StringProperty())) - .required("id"); - final DefaultCodegen codegen = new TypeScriptAngularJsClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 2); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "number"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "undefined"); - Assert.assertEquals(property1.baseType, "number"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "urls"); - Assert.assertEquals(property2.datatype, "Array"); - Assert.assertEquals(property2.name, "urls"); - Assert.assertEquals(property2.baseType, "Array"); - Assert.assertFalse(property2.hasMore); - Assert.assertFalse(property2.required); - Assert.assertTrue(property2.isContainer); - } - - @Test(description = "convert a model with complex property") - public void complexPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptAngularJsClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.datatype, "models.Children"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.defaultValue, "undefined"); - Assert.assertEquals(property1.baseType, "models.Children"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isNotContainer); - } - - @Test(description = "convert a model with complex list property") - public void complexListPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); - final DefaultCodegen codegen = new TypeScriptAngularJsClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.complexType, "models.Children"); - Assert.assertEquals(property1.datatype, "Array"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.baseType, "Array"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - } - - @Test(description = "convert an array model") - public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptAngularJsClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "an array model"); - Assert.assertEquals(cm.vars.size(), 0); - } - - @Test(description = "convert a map model") - public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptAngularJsClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a map model"); - Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("models.Children")).size(), 1); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java deleted file mode 100644 index e58a8a823c05..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openapitools.codegen.typescript.typescriptnode; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen; -import org.openapitools.codegen.options.TypeScriptNodeClientOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class TypeScriptNodeClientOptionsTest extends AbstractOptionsTest { - - @Tested - private TypeScriptNodeClientCodegen clientCodegen; - - public TypeScriptNodeClientOptionsTest() { - super(new TypeScriptNodeClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(TypeScriptNodeClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); - times = 1; - clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.SUPPORTS_ES6_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java deleted file mode 100644 index e3a2902863d6..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java +++ /dev/null @@ -1,188 +0,0 @@ -package org.openapitools.codegen.typescript.typescriptnode; - -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.*; - -import com.google.common.collect.Sets; -import org.testng.Assert; -import org.testng.annotations.Test; - -@SuppressWarnings("static-method") -public class TypeScriptNodeModelTest { - - @Test(description = "convert a simple TypeScript Node model") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .property("birthDate", new DateProperty()) - .required("id") - .required("name"); - final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 4); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "number"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "undefined"); - Assert.assertEquals(property1.baseType, "number"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.datatype, "string"); - Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "undefined"); - Assert.assertEquals(property2.baseType, "string"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.complexType, null); - Assert.assertEquals(property3.datatype, "Date"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, "undefined"); - Assert.assertTrue(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - - final CodegenProperty property4 = cm.vars.get(3); - Assert.assertEquals(property4.baseName, "birthDate"); - Assert.assertEquals(property4.complexType, null); - Assert.assertEquals(property4.datatype, "string"); - Assert.assertEquals(property4.name, "birthDate"); - Assert.assertEquals(property4.defaultValue, "undefined"); - Assert.assertFalse(property4.hasMore); - Assert.assertFalse(property4.required); - Assert.assertTrue(property4.isNotContainer); - } - - @Test(description = "convert a model with list property") - public void listPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty().items(new StringProperty())) - .required("id"); - final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 2); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "number"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "undefined"); - Assert.assertEquals(property1.baseType, "number"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "urls"); - Assert.assertEquals(property2.datatype, "Array"); - Assert.assertEquals(property2.name, "urls"); - Assert.assertEquals(property2.baseType, "Array"); - Assert.assertFalse(property2.hasMore); - Assert.assertFalse(property2.required); - Assert.assertTrue(property2.isContainer); - } - - @Test(description = "convert a model with complex property") - public void complexPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.datatype, "Children"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.baseType, "Children"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isNotContainer); - } - - @Test(description = "convert a model with complex list property") - public void complexListPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); - final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.datatype, "Array"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.baseType, "Array"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - } - - @Test(description = "convert an array model") - public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "an array model"); - Assert.assertEquals(cm.vars.size(), 0); - } - - @Test(description = "convert a map model") - public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a map model"); - Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java deleted file mode 100644 index 360d0d1114f7..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.openapitools.codegen.typescript.typescriptnode; - -import java.util.HashMap; -import java.util.Map; - -import org.openapitools.codegen.AbstractIntegrationTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen; -import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; - -public class TypescriptNodeES5IntegrationTest extends AbstractIntegrationTest { - - @Override - protected CodegenConfig getCodegenConfig() { - return new TypeScriptNodeClientCodegen(); - } - - @Override - protected Map configProperties() { - Map properties = new HashMap<>(); - properties.put("npmName", "node-es6-test"); - properties.put("npmVersion", "1.0.3"); - properties.put("snapshot", "false"); - properties.put("supportsES6", "false"); - - return properties; - } - - @Override - protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { - return new IntegrationTestPathsConfig("typescript/node-es5"); - } -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/utils/SemVerTest.java b/modules/openapi-generator/src/test/java/io/swagger/codegen/utils/SemVerTest.java deleted file mode 100644 index 1d2fd1cbce08..000000000000 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/utils/SemVerTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.openapitools.codegen.utils; - -import org.testng.annotations.Test; - -import static org.testng.Assert.*; - -public class SemVerTest { - - @Test - public void parsingAndPrinting() { - assertEquals("4.3.0", new SemVer("4.3").toString()); - } - - @Test - public void atLeast() { - assertTrue(new SemVer("3.2.1").atLeast("3.2.1")); - assertTrue(new SemVer("3.2.1").atLeast("2.3.4")); - assertFalse(new SemVer("3.2.1").atLeast("3.3.0")); - } - -} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/AbstractOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/AbstractOptionsTest.java similarity index 94% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/AbstractOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/AbstractOptionsTest.java index ea1c9c2c5b3d..10a2aae72121 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/AbstractOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/AbstractOptionsTest.java @@ -46,7 +46,7 @@ public void checkOptionsHelp() { final Set undocumented = new HashSet(testOptions); undocumented.removeAll(cliOptions); if (!undocumented.isEmpty()) { - Assert.fail(String.format("These options weren't documented: %s.", StringUtils.join(undocumented, ", "))); + Assert.fail(String.format("These options weren't documented: %s. Are you expecting base options and calling cliOptions.clear()?", StringUtils.join(undocumented, ", "))); } } 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 new file mode 100644 index 000000000000..5297ad66bdf6 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -0,0 +1,36 @@ +package org.openapitools.codegen; + +import org.testng.Assert; +import org.testng.annotations.Test; + +public class DefaultCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false ); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/android/AndroidClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/android/AndroidClientCodegenTest.java new file mode 100644 index 000000000000..d8bcc91f277a --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/android/AndroidClientCodegenTest.java @@ -0,0 +1,57 @@ +package org.openapitools.codegen.android; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.AndroidClientCodegen; + +public class AndroidClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final AndroidClientCodegen codegen = new AndroidClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertEquals(codegen.modelPackage(), "io.swagger.client.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "io.swagger.client.model"); + Assert.assertEquals(codegen.apiPackage(), "io.swagger.client.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "io.swagger.client.api"); + Assert.assertEquals(codegen.getInvokerPackage(), "io.swagger.client"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "io.swagger.client"); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final AndroidClientCodegen codegen = new AndroidClientCodegen(); + codegen.setModelPackage("xx.yyyyyyyy.model"); + codegen.setApiPackage("xx.yyyyyyyy.api"); + codegen.setInvokerPackage("xx.yyyyyyyy.invoker"); + 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.getInvokerPackage(), "xx.yyyyyyyy.invoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xx.yyyyyyyy.invoker"); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final AndroidClientCodegen codegen = new AndroidClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.mmmmm.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.aaaaa.api"); + codegen.additionalProperties().put(CodegenConstants.INVOKER_PACKAGE,"xyz.yyyyy.iiii.invoker"); + codegen.processOpts(); + + 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.getInvokerPackage(), "xyz.yyyyy.iiii.invoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.iiii.invoker"); + } +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/bash/BashClientOptionsTest.java similarity index 100% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/bash/BashClientOptionsTest.java diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/bash/BashTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/bash/BashTest.java similarity index 84% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/bash/BashTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/bash/BashTest.java index 885c592dac9e..1c29ba69e927 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/bash/BashTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/bash/BashTest.java @@ -4,9 +4,12 @@ import org.openapitools.codegen.CodegenParameter; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.languages.BashClientCodegen; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; + +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.parser.core.models.ParseOptions; + import org.testng.Assert; import org.testng.annotations.Test; @@ -16,20 +19,20 @@ public class BashTest { @Test(description = "test basic petstore operation with Bash extensions") public void petstoreOperationTest() { - final Swagger swagger - = new SwaggerParser() - .read("src/test/resources/2_0/petstore-bash.json"); + final OpenAPI openAPI + = new OpenAPIParser() + .readLocation("src/test/resources/2_0/petstore-bash.json", null, new ParseOptions()).getOpenAPI(); final DefaultCodegen codegen = new BashClientCodegen(); final Operation findPetsByStatusOperation - = swagger.getPath("/pet/findByStatus").getGet(); + = openAPI.getPaths().get("/pet/findByStatus").getGet(); final CodegenOperation op = codegen.fromOperation( "/pet/findByStatus", "GET", findPetsByStatusOperation, - swagger.getDefinitions(), - swagger); + openAPI.getComponents().getSchemas(), + openAPI); Assert.assertTrue( op.vendorExtensions.containsKey("x-code-samples")); @@ -43,20 +46,20 @@ public void petstoreOperationTest() { @Test(description = "test basic petstore operation with example body") public void petstoreParameterExampleTest() { - final Swagger swagger - = new SwaggerParser() - .read("src/test/resources/2_0/petstore-bash.json"); + final OpenAPI openAPI + = new OpenAPIParser() + .readLocation("src/test/resources/2_0/petstore-bash.json", null, new ParseOptions()).getOpenAPI(); final DefaultCodegen codegen = new BashClientCodegen(); final Operation addPetOperation - = swagger.getPath("/pet").getPost(); + = openAPI.getPaths().get("/pet").getPost(); final CodegenOperation op = codegen.fromOperation( "/pet", "POST", addPetOperation, - swagger.getDefinitions(), - swagger); + openAPI.getComponents().getSchemas(), + openAPI); Assert.assertEquals(op.bodyParams.size(), 1); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpClientCodegenTest.java new file mode 100644 index 000000000000..9b756972c7ad --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.csharp; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.CSharpClientCodegen; + +public class CSharpClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final CSharpClientCodegen codegen = new CSharpClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final CSharpClientCodegen codegen = new CSharpClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final CSharpClientCodegen codegen = new CSharpClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientCodegenTest.java new file mode 100644 index 000000000000..a93301679d03 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.dart; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.DartClientCodegen; + +public class DartClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final DartClientCodegen codegen = new DartClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final DartClientCodegen codegen = new DartClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final DartClientCodegen codegen = new DartClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientOptionsTest.java similarity index 100% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientOptionsTest.java diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/AbstractEiffelCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/AbstractEiffelCodegenTest.java new file mode 100644 index 000000000000..134a8c50385f --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/AbstractEiffelCodegenTest.java @@ -0,0 +1,57 @@ +package org.openapitools.codegen.eiffel; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.languages.AbstractEiffelCodegen; + +public class AbstractEiffelCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final AbstractEiffelCodegen codegen = new P_AbstractEiffelCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final AbstractEiffelCodegen codegen = new P_AbstractEiffelCodegen(); + codegen.setHideGenerationTimestamp(true); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final AbstractEiffelCodegen codegen = new P_AbstractEiffelCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, true); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + private static class P_AbstractEiffelCodegen extends AbstractEiffelCodegen { + @Override + public CodegenType getTag() { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public String getHelp() { + return null; + } + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/EiffelClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/EiffelClientCodegenTest.java new file mode 100644 index 000000000000..f96accbed8f7 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/EiffelClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.eiffel; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.EiffelClientCodegen; + +public class EiffelClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final EiffelClientCodegen codegen = new EiffelClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final EiffelClientCodegen codegen = new EiffelClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final EiffelClientCodegen codegen = new EiffelClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/elixir/ElixirClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/elixir/ElixirClientOptionsTest.java similarity index 93% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/elixir/ElixirClientOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/elixir/ElixirClientOptionsTest.java index 9d39b9e8078c..bc22e3c514f2 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/elixir/ElixirClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/elixir/ElixirClientOptionsTest.java @@ -4,7 +4,6 @@ import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.ElixirClientCodegen; import org.openapitools.codegen.options.ElixirClientOptionsProvider; -import org.openapitools.codegen.options.PhpClientOptionsProvider; import mockit.Expectations; import mockit.Tested; @@ -29,6 +28,7 @@ protected void setExpectations() { // TODO clientCodegen.setModuleName(ElixirClientOptionsProvider.INVOKER_PACKAGE_VALUE); times = 1; + }}; } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/AbstractGoCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/AbstractGoCodegenTest.java new file mode 100644 index 000000000000..891f3f739c28 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/AbstractGoCodegenTest.java @@ -0,0 +1,57 @@ +package org.openapitools.codegen.go; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.languages.AbstractGoCodegen; + +public class AbstractGoCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final AbstractGoCodegen codegen = new P_AbstractGoCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final AbstractGoCodegen codegen = new P_AbstractGoCodegen(); + codegen.setHideGenerationTimestamp(true); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final AbstractGoCodegen codegen = new P_AbstractGoCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, true); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + private static class P_AbstractGoCodegen extends AbstractGoCodegen { + @Override + public CodegenType getTag() { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public String getHelp() { + return null; + } + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java new file mode 100644 index 000000000000..01682665811e --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.go; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.GoClientCodegen; + +public class GoClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final GoClientCodegen codegen = new GoClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final GoClientCodegen codegen = new GoClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final GoClientCodegen codegen = new GoClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/go/GoClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientOptionsTest.java similarity index 87% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/go/GoClientOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientOptionsTest.java index a146f928d438..975fef860938 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/go/GoClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientOptionsTest.java @@ -32,6 +32,8 @@ protected void setExpectations() { times = 1; clientCodegen.setWithXml(GoClientOptionsProvider.WITH_XML_VALUE); times = 1; + clientCodegen.setPrependFormOrBodyParameters(Boolean.valueOf(GoClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); + times = 1; }}; } } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/go/GoModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoModelTest.java similarity index 82% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/go/GoModelTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoModelTest.java index e4ae8a1fefc7..a43a26154905 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/go/GoModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoModelTest.java @@ -1,18 +1,12 @@ package org.openapitools.codegen.go; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.languages.GoClientCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; +import org.openapitools.codegen.*; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.parser.util.SchemaTypeUtil; import com.google.common.collect.Sets; import org.testng.Assert; @@ -24,13 +18,13 @@ public class GoModelTest { @Test(description = "convert a simple Go model") public void simpleModelTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("name", new StringSchema()) + .addProperties("createdAt", new DateTimeSchema()) + .addRequiredItem("id") + .addRequiredItem("name"); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -76,12 +70,12 @@ public void simpleModelTest() { @Test(description = "convert a model with list property") public void listPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id"); + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("urls", new ArraySchema() + .items(new StringSchema())) + .addRequiredItem("id"); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -115,11 +109,11 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + .addProperties("translations", new MapSchema() + .additionalProperties(new StringSchema())) + .addRequiredItem("id"); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -141,9 +135,9 @@ public void mapPropertyTest() { @Test(description = "convert a model with complex property") public void complexPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); + .addProperties("children", new Schema().$ref("#/definitions/Children")); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -163,10 +157,10 @@ public void complexPropertyTest() { @Test(description = "convert a model with complex list property") public void complexListProperty() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); + .addProperties("children", new ArraySchema() + .items(new Schema().$ref("#/definitions/Children"))); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -187,10 +181,10 @@ public void complexListProperty() { @Test(description = "convert a model with complex map property") public void complexMapProperty() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); + .addProperties("children", new MapSchema() + .additionalProperties(new Schema().$ref("#/definitions/Children"))); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -214,9 +208,9 @@ public void complexMapProperty() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Schema model = new ArraySchema() + .items(new Schema().$ref("#/definitions/Children")) + .description("an array model"); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -229,9 +223,9 @@ public void arrayModelTest() { @Test(description = "convert an map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Schema model = new Schema() + .additionalProperties(new Schema().$ref("#/definitions/Children")) + .description("a map model"); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -258,7 +252,7 @@ public static Object[][] primeNumbers() { @Test(dataProvider = "modelNames", description = "avoid inner class") public void modelNameTest(String name, String expectedName) { - final Model model = new ModelImpl(); + final Schema model = new Schema(); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel(name, model); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellhttpclient/HaskellHttpClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellhttpclient/HaskellHttpClientCodegenTest.java new file mode 100644 index 000000000000..2913e6288ea2 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellhttpclient/HaskellHttpClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.haskellhttpclient; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.HaskellHttpClientCodegen; + +public class HaskellHttpClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final HaskellHttpClientCodegen codegen = new HaskellHttpClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final HaskellHttpClientCodegen codegen = new HaskellHttpClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final HaskellHttpClientCodegen codegen = new HaskellHttpClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/haskellservant/HaskellTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellservant/HaskellModelTest.java similarity index 60% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/haskellservant/HaskellTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellservant/HaskellModelTest.java index 2dcd6efa9aa9..73112fe9bfe6 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/haskellservant/HaskellTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellservant/HaskellModelTest.java @@ -1,17 +1,21 @@ package org.openapitools.codegen.haskellservant; +import io.swagger.v3.oas.models.PathItem; import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.languages.HaskellServantCodegen; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.parser.util.SchemaTypeUtil; import org.testng.Assert; import org.testng.annotations.Test; -public class HaskellTest { +public class HaskellModelTest { @Test(description = "convert a haskell model with dots") public void modelTest() { diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/haskellservant/HaskellServantOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellservant/HaskellServantOptionsTest.java similarity index 99% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/haskellservant/HaskellServantOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellservant/HaskellServantOptionsTest.java index eb09fc873b2f..f3c0b32cd335 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/haskellservant/HaskellServantOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellservant/HaskellServantOptionsTest.java @@ -1,5 +1,6 @@ package org.openapitools.codegen.haskellservant; + import org.openapitools.codegen.AbstractOptionsTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.HaskellServantCodegen; diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenTest.java new file mode 100644 index 000000000000..b6293f8b05a7 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenTest.java @@ -0,0 +1,107 @@ +package org.openapitools.codegen.java; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.languages.AbstractJavaCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class AbstractJavaCodegenTest { + + private final AbstractJavaCodegen fakeJavaCodegen = new P_AbstractJavaCodegen(); + + @Test + public void toEnumVarNameShouldNotShortenUnderScore() throws Exception { + Assert.assertEquals("UNDERSCORE", fakeJavaCodegen.toEnumVarName("_", "String")); + Assert.assertEquals("__", fakeJavaCodegen.toEnumVarName("__", "String")); + Assert.assertEquals("__", fakeJavaCodegen.toEnumVarName("_,.", "String")); + } + + @Test + public void toVarNameShouldAvoidOverloadingGetClassMethod() throws Exception { + Assert.assertEquals("propertyClass", fakeJavaCodegen.toVarName("class")); + Assert.assertEquals("propertyClass", fakeJavaCodegen.toVarName("_class")); + Assert.assertEquals("propertyClass", fakeJavaCodegen.toVarName("__class")); + } + + @Test + public void toModelNameShouldUseProvidedMapping() throws Exception { + fakeJavaCodegen.importMapping().put("json_myclass", "com.test.MyClass"); + Assert.assertEquals("com.test.MyClass", fakeJavaCodegen.toModelName("json_myclass")); + } + + @Test + public void toModelNameUsesPascalCase() throws Exception { + Assert.assertEquals("JsonAnotherclass", fakeJavaCodegen.toModelName("json_anotherclass")); + } + + @Test + public void testInitialConfigValues() throws Exception { + final AbstractJavaCodegen codegen = new P_AbstractJavaCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertEquals(codegen.modelPackage(), "invalidPackageName"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "invalidPackageName"); + Assert.assertEquals(codegen.apiPackage(), "invalidPackageName"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "invalidPackageName"); + Assert.assertEquals(codegen.getInvokerPackage(), "io.swagger"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "io.swagger"); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final AbstractJavaCodegen codegen = new P_AbstractJavaCodegen(); + codegen.setHideGenerationTimestamp(true); + codegen.setModelPackage("xyz.yyyyy.zzzzzzz.model"); + codegen.setApiPackage("xyz.yyyyy.zzzzzzz.api"); + codegen.setInvokerPackage("xyz.yyyyy.zzzzzzz.invoker"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.zzzzzzz.model"); + Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.zzzzzzz.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.zzzzzzz.api"); + Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.invoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.zzzzzzz.invoker"); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final AbstractJavaCodegen codegen = new P_AbstractJavaCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.model.oooooo"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.api.oooooo"); + codegen.additionalProperties().put(CodegenConstants.INVOKER_PACKAGE, "xyz.yyyyy.invoker.oooooo"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.model.oooooo"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.model.oooooo"); + Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.api.oooooo"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.api.oooooo"); + Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.invoker.oooooo"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.invoker.oooooo"); + } + + private static class P_AbstractJavaCodegen extends AbstractJavaCodegen { + @Override + public CodegenType getTag() { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public String getHelp() { + return null; + } + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaCXFClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaCXFClientCodegenTest.java new file mode 100644 index 000000000000..02772b7ea593 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaCXFClientCodegenTest.java @@ -0,0 +1,108 @@ +package org.openapitools.codegen.java; + +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.Content; +import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.media.ObjectSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.responses.ApiResponses; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenResponse; +import org.openapitools.codegen.languages.JavaCXFClientCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class JavaCXFClientCodegenTest { + + @Test + public void responseWithoutContent() throws Exception { + final Schema listOfPets = new ArraySchema().items(new Schema<>().$ref("#/components/schemas/Pet")); + Operation operation = new Operation() + .responses(new ApiResponses() + .addApiResponse("200", + new ApiResponse().description("Return a list of pets") + .content(new Content().addMediaType("application/json", + new MediaType().schema(listOfPets)))) + .addApiResponse("400", new ApiResponse().description("Error"))); + final Map allDefinitions = Collections.singletonMap("Pet", new ObjectSchema()); + + final JavaCXFClientCodegen codegen = new JavaCXFClientCodegen(); + final CodegenOperation co = codegen.fromOperation("getAllPets", "GET", operation, allDefinitions); + + Map objs = new HashMap<>(); + objs.put("operations", Collections.singletonMap("operation", Collections.singletonList(co))); + objs.put("imports", Collections.emptyList()); + codegen.postProcessOperations(objs); + + Assert.assertEquals(co.responses.size(), 2); + CodegenResponse cr1 = co.responses.get(0); + Assert.assertEquals(cr1.code, "200"); + Assert.assertEquals(cr1.baseType, "Pet"); + Assert.assertEquals(cr1.dataType, "List"); + Assert.assertFalse(cr1.vendorExtensions.containsKey("x-java-is-response-void")); + + CodegenResponse cr2 = co.responses.get(1); + Assert.assertEquals(cr2.code, "400"); + Assert.assertEquals(cr2.baseType, "Void"); + Assert.assertEquals(cr2.dataType, "void"); + Assert.assertEquals(cr2.vendorExtensions.get("x-java-is-response-void"), Boolean.TRUE); + } + + @Test + public void testInitialConfigValues() throws Exception { + final JavaCXFClientCodegen codegen = new JavaCXFClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + + Assert.assertEquals(codegen.modelPackage(), "io.swagger.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "io.swagger.model"); + Assert.assertEquals(codegen.apiPackage(), "io.swagger.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "io.swagger.api"); + Assert.assertEquals(codegen.getInvokerPackage(), "io.swagger.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "io.swagger.api"); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final JavaCXFClientCodegen codegen = new JavaCXFClientCodegen(); + codegen.setHideGenerationTimestamp(true); + codegen.setInvokerPackage("io.swagger.client.xyz.invoker"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertEquals(codegen.modelPackage(), "io.swagger.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "io.swagger.model"); + Assert.assertEquals(codegen.apiPackage(), "io.swagger.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "io.swagger.api"); + Assert.assertEquals(codegen.getInvokerPackage(), "io.swagger.client.xyz.invoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "io.swagger.client.xyz.invoker"); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final JavaCXFClientCodegen codegen = new JavaCXFClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "false"); + codegen.additionalProperties().put(CodegenConstants.INVOKER_PACKAGE,"io.swagger.client.xyz.invoker"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertEquals(codegen.modelPackage(), "io.swagger.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "io.swagger.model"); + Assert.assertEquals(codegen.apiPackage(), "io.swagger.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "io.swagger.api"); + Assert.assertEquals(codegen.getInvokerPackage(), "io.swagger.client.xyz.invoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "io.swagger.client.xyz.invoker"); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java new file mode 100644 index 000000000000..1628d9d90632 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java @@ -0,0 +1,293 @@ +package org.openapitools.codegen.java; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; + +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.Content; +import io.swagger.v3.oas.models.media.IntegerSchema; +import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.media.ObjectSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; +import io.swagger.v3.oas.models.parameters.RequestBody; +import io.swagger.v3.parser.util.SchemaTypeUtil; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenModelFactory; +import org.openapitools.codegen.CodegenModelType; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.languages.JavaClientCodegen; + +public class JavaClientCodegenTest { + + @Test + public void modelInheritanceSupportInGson() throws Exception { + List> allModels = new ArrayList<>(); + + CodegenModel parent1 = CodegenModelFactory.newInstance(CodegenModelType.MODEL); + parent1.setName("parent1"); + parent1.setClassname("test.Parent1"); + + Map modelMap = new HashMap<>(); + modelMap.put("model", parent1); + allModels.add(modelMap); + + CodegenModel parent2 = CodegenModelFactory.newInstance(CodegenModelType.MODEL); + parent2.setName("parent2"); + parent2.setClassname("test.Parent2"); + + modelMap = new HashMap<>(); + modelMap.put("model", parent2); + allModels.add(modelMap); + + CodegenModel model1 = CodegenModelFactory.newInstance(CodegenModelType.MODEL); + model1.setName("model1"); + model1.setClassname("test.Model1"); + model1.setParentModel(parent1); + + modelMap = new HashMap<>(); + modelMap.put("model", model1); + allModels.add(modelMap); + + CodegenModel model2 = CodegenModelFactory.newInstance(CodegenModelType.MODEL); + model2.setName("model2"); + model2.setClassname("test.Model2"); + model2.setParentModel(parent1); + + modelMap = new HashMap<>(); + modelMap.put("model", model2); + allModels.add(modelMap); + + CodegenModel model3 = CodegenModelFactory.newInstance(CodegenModelType.MODEL); + model3.setName("model3"); + model3.setClassname("test.Model3"); + model3.setParentModel(parent1); + + modelMap = new HashMap<>(); + modelMap.put("model", model3); + allModels.add(modelMap); + + CodegenModel model4 = CodegenModelFactory.newInstance(CodegenModelType.MODEL); + model4.setName("model4"); + model4.setClassname("test.Model4"); + model4.setParentModel(parent2); + + modelMap = new HashMap<>(); + modelMap.put("model", model4); + allModels.add(modelMap); + + CodegenModel model5 = CodegenModelFactory.newInstance(CodegenModelType.MODEL); + model5.setName("model5"); + model5.setClassname("test.Model5"); + model5.setParentModel(parent2); + + modelMap = new HashMap<>(); + modelMap.put("model", model5); + allModels.add(modelMap); + + List> parentsList = JavaClientCodegen.modelInheritanceSupportInGson(allModels); + + Assert.assertNotNull(parentsList); + Assert.assertEquals(parentsList.size(), 2); + + Map parent = parentsList.get(0); + Assert.assertEquals(parent.get("classname"), "test.Parent1"); + + List children = (List) parent.get("children"); + Assert.assertNotNull(children); + Assert.assertEquals(children.size(), 3); + + Map models = (Map) children.get(0); + Assert.assertEquals(models.get("name"), "model1"); + Assert.assertEquals(models.get("classname"), "test.Model1"); + + models = (Map) children.get(1); + Assert.assertEquals(models.get("name"), "model2"); + Assert.assertEquals(models.get("classname"), "test.Model2"); + + models = (Map) children.get(2); + Assert.assertEquals(models.get("name"), "model3"); + Assert.assertEquals(models.get("classname"), "test.Model3"); + + parent = parentsList.get(1); + Assert.assertEquals(parent.get("classname"), "test.Parent2"); + + children = (List) parent.get("children"); + Assert.assertNotNull(children); + Assert.assertEquals(children.size(), 2); + + models = (Map) children.get(0); + Assert.assertEquals(models.get("name"), "model4"); + Assert.assertEquals(models.get("classname"), "test.Model4"); + + models = (Map) children.get(1); + Assert.assertEquals(models.get("name"), "model5"); + Assert.assertEquals(models.get("classname"), "test.Model5"); + } + + @Test + public void arraysInRequestBody() throws Exception { + final JavaClientCodegen codegen = new JavaClientCodegen(); + + RequestBody body1 = new RequestBody(); + body1.setDescription("A list of ids"); + body1.setContent(new Content().addMediaType("application/json", new MediaType().schema(new ArraySchema().items(new StringSchema())))); + CodegenParameter codegenParameter1 = codegen.fromRequestBody(body1 , new HashMap(), new HashSet()); + + RequestBody body2 = new RequestBody(); + body2.setDescription("A list of list of values"); + body2.setContent(new Content().addMediaType("application/json", new MediaType().schema(new ArraySchema().items(new ArraySchema().items(new IntegerSchema()))))); + CodegenParameter codegenParameter2 = codegen.fromRequestBody(body2 , new HashMap(), new HashSet()); + + RequestBody body3 = new RequestBody(); + body3.setDescription("A list of points"); + body3.setContent(new Content().addMediaType("application/json", new MediaType().schema(new ArraySchema().items(new ObjectSchema().$ref("#/components/schemas/Point"))))); + ObjectSchema point = new ObjectSchema(); + point.addProperties("message", new StringSchema()); + point.addProperties("x", new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)); + point.addProperties("y", new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)); + CodegenParameter codegenParameter3 = codegen.fromRequestBody(body3 , Collections.singletonMap("Point", point), new HashSet()); + } + + @Test + public void testParametersAreCorrectlyOrderedWhenUsingRetrofit(){ + JavaClientCodegen javaClientCodegen = new JavaClientCodegen(); + javaClientCodegen.setLibrary(JavaClientCodegen.RETROFIT_2); + + CodegenOperation codegenOperation = new CodegenOperation(); + CodegenParameter queryParamRequired = createQueryParam("queryParam1", true); + CodegenParameter queryParamOptional = createQueryParam("queryParam2", false); + CodegenParameter pathParam1 = createPathParam("pathParam1"); + CodegenParameter pathParam2 = createPathParam("pathParam2"); + + codegenOperation.allParams = Arrays.asList(queryParamRequired, pathParam1, pathParam2, queryParamOptional); + Map operations = ImmutableMap.of("operation", Arrays.asList(codegenOperation)); + + Map objs = ImmutableMap.of("operations", operations, "imports", new ArrayList>()); + + javaClientCodegen.postProcessOperations(objs); + + Assert.assertEquals(Arrays.asList(pathParam1, pathParam2, queryParamRequired, queryParamOptional), codegenOperation.allParams); + Assert.assertTrue(pathParam1.hasMore); + Assert.assertTrue(pathParam2.hasMore); + Assert.assertTrue(queryParamRequired.hasMore); + Assert.assertFalse(queryParamOptional.hasMore); + } + + @Test + public void testInitialConfigValues() throws Exception { + final JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + + Assert.assertEquals(codegen.modelPackage(), "io.swagger.client.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "io.swagger.client.model"); + Assert.assertEquals(codegen.apiPackage(), "io.swagger.client.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "io.swagger.client.api"); + Assert.assertEquals(codegen.getInvokerPackage(), "io.swagger.client"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "io.swagger.client"); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.setHideGenerationTimestamp(true); + codegen.setModelPackage("xyz.yyyyy.zzzzzzz.model"); + codegen.setApiPackage("xyz.yyyyy.zzzzzzz.api"); + codegen.setInvokerPackage("xyz.yyyyy.zzzzzzz.invoker"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.zzzzzzz.model"); + Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.zzzzzzz.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.zzzzzzz.api"); + Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.invoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.zzzzzzz.invoker"); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true"); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); + codegen.additionalProperties().put(CodegenConstants.INVOKER_PACKAGE,"xyz.yyyyy.zzzzzzz.iiii.invoker"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.zzzzzzz.aaaaa.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.zzzzzzz.aaaaa.api"); + Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.iiii.invoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.zzzzzzz.iiii.invoker"); + } + + @Test + public void testPackageNamesSetInvokerDerivedFromApi() throws Exception { + final JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); + codegen.processOpts(); + + Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.zzzzzzz.aaaaa.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.zzzzzzz.aaaaa.api"); + Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.aaaaa"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.zzzzzzz.aaaaa"); + } + + @Test + public void testPackageNamesSetInvokerDerivedFromModel() throws Exception { + final JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen.processOpts(); + + Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals(codegen.apiPackage(), "io.swagger.client.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "io.swagger.client.api"); + Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.mmmmm"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.zzzzzzz.mmmmm"); + } + + private CodegenParameter createPathParam(String name) { + CodegenParameter codegenParameter = createStringParam(name); + codegenParameter.isPathParam = true; + return codegenParameter; + } + + private CodegenParameter createQueryParam(String name, boolean required) { + CodegenParameter codegenParameter = createStringParam(name); + codegenParameter.isQueryParam = true; + codegenParameter.required = required; + return codegenParameter; + } + + private CodegenParameter createStringParam(String name){ + CodegenParameter codegenParameter = new CodegenParameter(); + codegenParameter.paramName = name; + codegenParameter.baseName = name; + codegenParameter.dataType = "String"; + return codegenParameter; + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaInheritanceTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaInheritanceTest.java new file mode 100644 index 000000000000..9c4169ec025f --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaInheritanceTest.java @@ -0,0 +1,59 @@ +package org.openapitools.codegen.java; + +import com.google.common.collect.Sets; +import io.swagger.v3.oas.models.media.ComposedSchema; +import io.swagger.v3.oas.models.media.Discriminator; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.languages.JavaClientCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.HashMap; +import java.util.Map; + +public class JavaInheritanceTest { + + @Test(description = "convert a composed model with parent") + public void javaInheritanceTest() { + final Schema parentModel = new Schema().name("Base"); + + final Schema schema = new ComposedSchema() + .addAllOfItem(new Schema().$ref("Base")) + .name("composed"); + + final Map allSchemas = new HashMap<>(); + allSchemas.put(parentModel.getName(), parentModel); + allSchemas.put(schema.getName(), schema); + + final JavaClientCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", schema, allSchemas); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.parent, "Base"); + Assert.assertEquals(cm.imports, Sets.newHashSet("Base")); + } + + @Test(description = "convert a composed model with discriminator") + public void javaInheritanceWithDiscriminatorTest() { + final Schema base = new Schema().name("Base"); + base.setDiscriminator(new Discriminator().mapping("name", StringUtils.EMPTY)); + + final Schema schema = new ComposedSchema() + .addAllOfItem(new Schema().$ref("Base")); + + final Map allDefinitions = new HashMap(); + allDefinitions.put("Base", base); + + final JavaClientCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", schema, allDefinitions); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.parent, "Base"); + Assert.assertEquals(cm.imports, Sets.newHashSet("Base")); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelEnumTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelEnumTest.java new file mode 100644 index 000000000000..4c4cb9722e98 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelEnumTest.java @@ -0,0 +1,74 @@ +package org.openapitools.codegen.java; + +import io.swagger.v3.oas.models.media.ComposedSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; + +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.languages.JavaClientCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class JavaModelEnumTest { + @Test(description = "convert a java model with an enum") + public void converterTest() { + final StringSchema enumSchema = new StringSchema(); + enumSchema.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); + final Schema model = new Schema().type("object").addProperties("name", enumSchema); + + final JavaClientCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty enumVar = cm.vars.get(0); + Assert.assertEquals(enumVar.baseName, "name"); + Assert.assertEquals(enumVar.datatype, "String"); + Assert.assertEquals(enumVar.datatypeWithEnum, "NameEnum"); + Assert.assertEquals(enumVar.name, "name"); + Assert.assertEquals(enumVar.defaultValue, "null"); + Assert.assertEquals(enumVar.baseType, "String"); + Assert.assertTrue(enumVar.isEnum); + } + + @Test(description = "not override identical parent enums") + public void overrideEnumTest() { + final StringSchema identicalEnumProperty = new StringSchema(); + identicalEnumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); + + final StringSchema subEnumProperty = new StringSchema(); + subEnumProperty.setEnum(Arrays.asList("SUB1", "SUB2", "SUB3")); + + // Add one enum property to the parent + final Map parentProperties = new HashMap<>(); + parentProperties.put("sharedThing", identicalEnumProperty); + + // Add TWO enums to the subType model; one of which is identical to the one in parent class + final Map subProperties = new HashMap<>(); + subProperties.put("unsharedThing", subEnumProperty); + + final Schema parentModel = new Schema(); + parentModel.setProperties(parentProperties); + parentModel.name("parentModel"); + + final ComposedSchema composedSchema = new ComposedSchema() + .addAllOfItem(new Schema().$ref(parentModel.getName())); + + final JavaClientCodegen codegen = new JavaClientCodegen(); + final Map allModels = new HashMap(); + allModels.put(parentModel.getName(), parentModel); + allModels.put(composedSchema.getName(), composedSchema); + + final CodegenModel cm = codegen.fromModel("sample", composedSchema, allModels); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.parent, "ParentModel"); + Assert.assertTrue(cm.imports.contains("ParentModel")); + } +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java similarity index 60% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaModelTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java index 7aa84c14cb01..1994c051ebbc 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java @@ -1,45 +1,60 @@ package org.openapitools.codegen.java; import com.google.common.collect.Sets; + +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.ByteArraySchema; +import io.swagger.v3.oas.models.media.Content; +import io.swagger.v3.oas.models.media.DateTimeSchema; +import io.swagger.v3.oas.models.media.IntegerSchema; +import io.swagger.v3.oas.models.media.MapSchema; +import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.media.NumberSchema; +import io.swagger.v3.oas.models.media.ObjectSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; +import io.swagger.v3.oas.models.media.XML; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.parameters.QueryParameter; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.responses.ApiResponses; +import io.swagger.v3.parser.util.SchemaTypeUtil; + +import org.junit.rules.TemporaryFolder; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; import org.openapitools.codegen.CodegenParameter; import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenResponse; import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.languages.JavaClientCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Xml; -import io.swagger.models.parameters.QueryParameter; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.ByteArrayProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DecimalProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.io.File; +import java.util.Collections; import java.util.List; +import java.util.Map; -@SuppressWarnings("static-method") public class JavaModelTest { + private TemporaryFolder folder = new TemporaryFolder(); @Test(description = "convert a simple java model") public void simpleModelTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty() + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("name", new StringSchema() .example("Tony")) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); + .addProperties("createdAt", new DateTimeSchema()) + .addRequiredItem("id") + .addRequiredItem("name"); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -90,14 +105,14 @@ public void simpleModelTest() { @Test(description = "convert a model with list property") public void listPropertyTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id"); + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("urls", new ArraySchema() + .items(new StringSchema())) + .addRequiredItem("id"); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -119,13 +134,13 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + .addProperties("translations", new MapSchema() + .additionalProperties(new StringSchema())) + .addRequiredItem("id"); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -147,13 +162,13 @@ public void mapPropertyTest() { @Test(description = "convert a model with a map with complex list property") public void mapWithListPropertyTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .property("translations", - new MapProperty().additionalProperties(new ArrayProperty().items(new RefProperty("Pet")))) - .required("id"); + .addProperties("translations", new MapSchema() + .additionalProperties(new ArraySchema().items(new Schema().$ref("Pet")))) + .addRequiredItem("id"); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -175,8 +190,10 @@ public void mapWithListPropertyTest() { @Test(description = "convert a model with a 2D list property") public void list2DPropertyTest() { - final Model model = new ModelImpl().name("sample").property("list2D", new ArrayProperty().items( - new ArrayProperty().items(new RefProperty("Pet")))); + final Schema model = new Schema() + .name("sample") + .addProperties("list2D", new ArraySchema().items( + new ArraySchema().items(new Schema().$ref("Pet")))); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -197,10 +214,11 @@ public void list2DPropertyTest() { @Test(description = "convert a model with complex properties") public void complexPropertiesTest() { - final Model model = new ModelImpl().description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); + final Schema schema = new Schema() + .description("a sample model") + .addProperties("children", new Schema().$ref("#/components/schemas/Children")); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -221,11 +239,12 @@ public void complexPropertiesTest() { @Test(description = "convert a model with complex list property") public void complexListPropertyTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .property("children", new ArrayProperty().items(new RefProperty("#/definitions/Children"))); + .addProperties("children", new ArraySchema() + .items(new Schema().$ref("#/components/schemas/Children"))); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -248,11 +267,12 @@ public void complexListPropertyTest() { @Test(description = "convert a model with complex map property") public void complexMapPropertyTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .property("children", new MapProperty().additionalProperties(new RefProperty("#/definitions/Children"))); + .addProperties("children", new MapSchema() + .additionalProperties(new Schema().$ref("#/components/schemas/Children"))); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -278,14 +298,18 @@ public void complexMapPropertyTest() { @Test(description = "convert a model with an array property with item name") public void arrayModelWithItemNameTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .description("an array property") - .items(new RefProperty("#/definitions/Child")) - .vendorExtension("x-item-name", "child")); + final Schema propertySchema = new ArraySchema() + .items(new Schema().$ref("#/components/schemas/Child")) + .description("an array property"); + propertySchema.addExtension("x-item-name", "child"); + final Schema schema = new Schema() + .type("object") + .description("a sample model") + .addProperties("children", propertySchema); + + final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -314,11 +338,12 @@ public void arrayModelWithItemNameTest() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Schema schema = new ArraySchema() + .items(new Schema().name("elobjeto").$ref("#/components/schemas/Children")) + .name("arraySchema") + .description("an array model"); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -331,11 +356,11 @@ public void arrayModelTest() { @Test(description = "convert an map model") public void mapModelTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("an map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + .additionalProperties(new Schema().$ref("#/components/schemas/Children")); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -348,12 +373,12 @@ public void mapModelTest() { @Test(description = "convert a model with upper-case property names") public void upperCaseNamesTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a model with upper-case property names") - .property("NAME", new StringProperty()) - .required("NAME"); + .addProperties("NAME", new StringSchema()) + .addRequiredItem("NAME"); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -374,12 +399,12 @@ public void upperCaseNamesTest() { @Test(description = "convert a model with a 2nd char upper-case property names") public void secondCharUpperCaseNamesTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a model with a 2nd char upper-case property names") - .property("pId", new StringProperty()) - .required("pId"); + .addProperties("pId", new StringSchema()) + .addRequiredItem("pId"); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -400,12 +425,12 @@ public void secondCharUpperCaseNamesTest() { @Test(description = "convert a model starting with two upper-case letter property names") public void firstTwoUpperCaseLetterNamesTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a model with a property name starting with two upper-case letters") - .property("ATTName", new StringProperty()) - .required("ATTName"); + .addProperties("ATTName", new StringSchema()) + .addRequiredItem("ATTName"); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -426,11 +451,11 @@ public void firstTwoUpperCaseLetterNamesTest() { @Test(description = "convert hyphens per issue 503") public void hyphensTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .property("created-at", new DateTimeProperty()); + .addProperties("created-at", new DateTimeSchema()); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); final CodegenProperty property = cm.vars.get(0); Assert.assertEquals(property.baseName, "created-at"); @@ -441,11 +466,11 @@ public void hyphensTest() { @Test(description = "convert query[password] to queryPassword") public void squareBracketsTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .property("query[password]", new StringProperty()); + .addProperties("query[password]", new StringSchema()); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); final CodegenProperty property = cm.vars.get(0); Assert.assertEquals(property.baseName, "query[password]"); @@ -456,22 +481,22 @@ public void squareBracketsTest() { @Test(description = "properly escape names per 567") public void escapeNamesTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .property("created-at", new DateTimeProperty()); + .addProperties("created-at", new DateTimeSchema()); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("with.dots", model); + final CodegenModel cm = codegen.fromModel("with.dots", schema); Assert.assertEquals(cm.classname, "WithDots"); } @Test(description = "convert a model with binary data") public void binaryDataTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("model with binary") - .property("inputBinaryData", new ByteArrayProperty()); + .addProperties("inputBinaryData", new ByteArraySchema()); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); final CodegenProperty property = cm.vars.get(0); Assert.assertEquals(property.baseName, "inputBinaryData"); @@ -488,11 +513,11 @@ public void binaryDataTest() { @Test(description = "translate an invalid param name") public void invalidParamNameTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a model with a 2nd char upper-case property names") - .property("_", new StringProperty()); + .addProperties("_", new StringSchema()); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -512,8 +537,7 @@ public void invalidParamNameTest() { @Test(description = "convert a parameter") public void convertParameterTest() { - final QueryParameter parameter = new QueryParameter() - .property(new IntegerProperty()) + final Parameter parameter = new QueryParameter() .name("limit") .required(true); final DefaultCodegen codegen = new JavaClientCodegen(); @@ -524,15 +548,18 @@ public void convertParameterTest() { @Test(description = "types used by inner properties should be imported") public void mapWithAnListOfBigDecimalTest() { - final CodegenModel cm1 = new JavaClientCodegen().fromModel("sample", new ModelImpl() + final CodegenModel cm1 = new JavaClientCodegen().fromModel("sample", new Schema() .description("model with Map>") - .property("map", new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty())))); + .addProperties("map", new MapSchema() + .additionalProperties(new ArraySchema().items(new NumberSchema())))); Assert.assertEquals(cm1.vars.get(0).datatype, "Map>"); Assert.assertTrue(cm1.imports.contains("BigDecimal")); - final CodegenModel cm2 = new JavaClientCodegen().fromModel("sample", new ModelImpl() + final CodegenModel cm2 = new JavaClientCodegen().fromModel("sample", new Schema() .description("model with Map>>") - .property("map", new MapProperty().additionalProperties(new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty()))))); + .addProperties("map", new MapSchema() + .additionalProperties(new MapSchema() + .additionalProperties(new ArraySchema().items(new NumberSchema()))))); Assert.assertEquals(cm2.vars.get(0).datatype, "Map>>"); Assert.assertTrue(cm2.imports.contains("BigDecimal")); } @@ -553,9 +580,9 @@ public static Object[][] primeNumbers() { @Test(dataProvider = "modelNames", description = "avoid inner class") public void modelNameTest(String name, String expectedName) { - final Model model = new ModelImpl(); + final Schema schema = new Schema(); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel(name, model); + final CodegenModel cm = codegen.fromModel(name, schema); Assert.assertEquals(cm.name, name); Assert.assertEquals(cm.classname, expectedName); @@ -572,11 +599,11 @@ public static Object[][] classProperties() { @Test(dataProvider = "classProperties", description = "handle 'class' properties") public void classPropertyTest(String baseName, String getter, String setter, String name) { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .property(baseName, new StringProperty()); + .addProperties(baseName, new StringSchema()); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); final CodegenProperty property = cm.vars.get(0); Assert.assertEquals(property.baseName, baseName); @@ -588,28 +615,28 @@ public void classPropertyTest(String baseName, String getter, String setter, Str @Test(description = "test models with xml") public void modelWithXmlTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .xml(new Xml() - .prefix("my") - .namespace("xmlNamespace") - .name("customXmlName")) - .property("id", new LongProperty()) - .property("name", new StringProperty() - .example("Tony") - .xml(new Xml() - .attribute(true) - .prefix("my") - .name("myName"))) - .property("createdAt", new DateTimeProperty() - .xml(new Xml() - .prefix("my") - .namespace("myNamespace") - .name("myCreatedAt"))) - .required("id") - .required("name"); + .xml(new XML() + .prefix("my") + .namespace("xmlNamespace") + .name("customXmlName")) + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("name", new StringSchema() + .example("Tony") + .xml(new XML() + .attribute(true) + .prefix("my") + .name("myName"))) + .addProperties("createdAt", new DateTimeSchema() + .xml(new XML() + .prefix("my") + .namespace("myNamespace") + .name("myCreatedAt"))) + .addRequiredItem("id") + .addRequiredItem("name"); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -656,24 +683,25 @@ public void modelWithXmlTest() { @Test(description = "test models with wrapped xml") public void modelWithWrappedXmlTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .xml(new Xml() - .prefix("my") - .namespace("xmlNamespace") - .name("customXmlName")) - .property("id", new LongProperty()) - .property("array", new ArrayProperty() - .xml(new Xml() - .prefix("my") - .wrapped(true) - .namespace("myNamespace") - .name("xmlArray")).items(new StringProperty() - .xml(new Xml() - .name("i")))) - .required("id"); + .xml(new XML() + .prefix("my") + .namespace("xmlNamespace") + .name("customXmlName")) + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("array", new ArraySchema() + .items(new StringSchema() + .xml(new XML() + .name("i"))) + .xml(new XML() + .prefix("my") + .wrapped(true) + .namespace("myNamespace") + .name("xmlArray"))) + .addRequiredItem("id"); final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -703,19 +731,177 @@ public void modelWithWrappedXmlTest() { Assert.assertEquals(items.baseName, "array"); } - @Test(description = "convert a boolean parameter") - public void booleanParameterTest() { - final BooleanProperty property = new BooleanProperty(); + @Test(description = "convert an integer property") + public void integerPropertyTest() { + final IntegerSchema property = new IntegerSchema(); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenProperty cp = codegen.fromProperty("property", property); + + Assert.assertEquals(cp.baseName, "property"); + Assert.assertEquals(cp.datatype, "Integer"); + Assert.assertEquals(cp.name, "property"); + Assert.assertEquals(cp.baseType, "Integer"); + Assert.assertTrue(cp.isNotContainer); + Assert.assertTrue(cp.isInteger); + Assert.assertFalse(cp.isLong); + Assert.assertEquals(cp.getter, "getProperty"); + } + + @Test(description = "convert a long property") + public void longPropertyTest() { + final IntegerSchema property = new IntegerSchema().format("int64"); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenProperty cp = codegen.fromProperty("property", property); Assert.assertEquals(cp.baseName, "property"); - Assert.assertEquals(cp.datatype, "Boolean"); + Assert.assertEquals(cp.datatype, "Long"); Assert.assertEquals(cp.name, "property"); - Assert.assertEquals(cp.baseType, "Boolean"); + Assert.assertEquals(cp.baseType, "Long"); Assert.assertTrue(cp.isNotContainer); - Assert.assertTrue(cp.isBoolean); - Assert.assertEquals(cp.getter, "Property"); + Assert.assertTrue(cp.isLong); + Assert.assertFalse(cp.isInteger); + Assert.assertEquals(cp.getter, "getProperty"); + } + + @Test(description = "convert an integer property in a referenced schema") + public void integerPropertyInReferencedSchemaTest() { + final IntegerSchema longProperty = new IntegerSchema().format("int32"); + final Schema testSchema = new ObjectSchema() + .addProperties("Integer1", new Schema<>().$ref("#/components/schemas/IntegerProperty")) + .addProperties("Integer2", new IntegerSchema().format("int32")); + final Map allDefinitions = Collections. singletonMap("IntegerProperty", longProperty); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("test", testSchema, allDefinitions); + + Assert.assertEquals(cm.vars.size(), 2); + + CodegenProperty cp1 = cm.vars.get(0); + Assert.assertEquals(cp1.baseName, "Integer1"); + Assert.assertEquals(cp1.datatype, "Integer"); + Assert.assertEquals(cp1.name, "integer1"); + Assert.assertEquals(cp1.baseType, "Integer"); + Assert.assertEquals(cp1.getter, "getInteger1"); + + CodegenProperty cp2 = cm.vars.get(1); + Assert.assertEquals(cp2.baseName, "Integer2"); + Assert.assertEquals(cp2.datatype, "Integer"); + Assert.assertEquals(cp2.name, "integer2"); + Assert.assertEquals(cp2.baseType, "Integer"); + Assert.assertEquals(cp2.getter, "getInteger2"); } + @Test(description = "convert an array schema") + public void arraySchemaTest() { + final Schema testSchema = new ObjectSchema() + .addProperties("pets", new ArraySchema() + .items(new Schema<>().$ref("#/components/schemas/Pet"))); + final Map allDefinitions = Collections. singletonMap("Pet", new ObjectSchema()); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("test", testSchema, allDefinitions); + + Assert.assertEquals(cm.vars.size(), 1); + CodegenProperty cp1 = cm.vars.get(0); + Assert.assertEquals(cp1.baseName, "pets"); + Assert.assertEquals(cp1.datatype, "List"); + Assert.assertEquals(cp1.name, "pets"); + Assert.assertEquals(cp1.baseType, "List"); + Assert.assertEquals(cp1.getter, "getPets"); + + Assert.assertTrue(cm.imports.contains("List")); + Assert.assertTrue(cm.imports.contains("Pet")); + } + +// @Test(description = "convert an array schema in a RequestBody") +// public void arraySchemaTestInRequestBody() { +// final Schema testSchema = new ArraySchema() +// .items(new Schema<>().$ref("#/components/schemas/Pet")); +// Operation operation = new Operation() +// .requestBody(new RequestBody() +// .content(new Content().addMediaType("application/json", +// new MediaType().schema(testSchema)))) +// .responses( +// new ApiResponses().addApiResponse("204", new ApiResponse() +// .description("Ok response"))); +// final Map allDefinitions = Collections. singletonMap("Pet", new ObjectSchema()); +// final DefaultCodegen codegen = new JavaClientCodegen(); +// final CodegenOperation co = codegen.fromOperation("testSchema", "GET", operation, allDefinitions); +// +// Assert.assertEquals(co.bodyParams.size(), 1); +// CodegenParameter cp1 = co.bodyParams.get(0); +// Assert.assertEquals(cp1.baseType, "Pet"); +// Assert.assertEquals(cp1.dataType, "List"); +// Assert.assertEquals(cp1.items.baseType, "Pet"); +// Assert.assertEquals(cp1.items.complexType, "Pet"); +// Assert.assertEquals(cp1.items.datatype, "List"); +// +// Assert.assertEquals(co.responses.size(), 1); +// +// Assert.assertTrue(co.imports.contains("Pet")); +// } + + @Test(description = "convert an array schema in a ApiResponse") + public void arraySchemaTestInOperationResponse() { + final Schema testSchema = new ArraySchema() + .items(new Schema<>().$ref("#/components/schemas/Pet")); + Operation operation = new Operation().responses( + new ApiResponses().addApiResponse("200", new ApiResponse() + .description("Ok response") + .content(new Content().addMediaType("application/json", + new MediaType().schema(testSchema))))); + final Map allDefinitions = Collections. singletonMap("Pet", new ObjectSchema()); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenOperation co = codegen.fromOperation("testSchema", "GET", operation, allDefinitions); + + Assert.assertEquals(co.responses.size(), 1); + CodegenResponse cr = co.responses.get(0); + Assert.assertEquals(cr.baseType, "Pet"); + Assert.assertEquals(cr.dataType, "List"); + Assert.assertEquals(cr.containerType, "array"); + + Assert.assertTrue(co.imports.contains("Pet")); + } + + @Test(description = "convert a array of array schema") + public void arrayOfArraySchemaTest() { + final Schema testSchema = new ObjectSchema() + .addProperties("pets", new ArraySchema() + .items(new ArraySchema() + .items(new Schema<>().$ref("#/components/schemas/Pet")))); + final Map allDefinitions = Collections. singletonMap("Pet", new ObjectSchema()); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("test", testSchema, allDefinitions); + + Assert.assertEquals(cm.vars.size(), 1); + CodegenProperty cp1 = cm.vars.get(0); + Assert.assertEquals(cp1.baseName, "pets"); + Assert.assertEquals(cp1.datatype, "List>"); + Assert.assertEquals(cp1.name, "pets"); + Assert.assertEquals(cp1.baseType, "List"); + Assert.assertEquals(cp1.getter, "getPets"); + + Assert.assertTrue(cm.imports.contains("List")); + Assert.assertTrue(cm.imports.contains("Pet")); + } + + @Test(enabled = false, description = "disabled since templates have been moved.") + public void generateModel() throws Exception { + folder.create(); + final File output = folder.getRoot(); + getClass().getClassLoader().getResourceAsStream("src/test/resources/3_0_0/petstore.json"); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setLang("java") + .setLibrary("jersey2") + //.addAdditionalProperty("withXml", true) + .addAdditionalProperty(CodegenConstants.SERIALIZABLE_MODEL, true) + .setInputSpec("src/test/resources/3_0_0/petstore.json") + .setOutputDir(output.getAbsolutePath()); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + new DefaultGenerator().opts(clientOptInput).generate(); + + File orderFile = new File(output, "src/main/java/io/swagger/client/model/Order.java"); + Assert.assertTrue(orderFile.exists()); + folder.delete(); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/AbstractJavaJAXRSServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/AbstractJavaJAXRSServerCodegenTest.java new file mode 100644 index 000000000000..43dc0abc8024 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/AbstractJavaJAXRSServerCodegenTest.java @@ -0,0 +1,93 @@ +package org.openapitools.codegen.java.jaxrs; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.languages.AbstractJavaJAXRSServerCodegen; + +public class AbstractJavaJAXRSServerCodegenTest { + + private final AbstractJavaJAXRSServerCodegen fakeJavaJAXRSCodegen = new P_AbstractJavaJAXRSServerCodegen(); + + @Test + public void convertApiName() throws Exception { + Assert.assertEquals(fakeJavaJAXRSCodegen.toApiName("name"), "NameApi"); + Assert.assertEquals(fakeJavaJAXRSCodegen.toApiName("$name"), "NameApi"); + Assert.assertEquals(fakeJavaJAXRSCodegen.toApiName("nam#e"), "NameApi"); + Assert.assertEquals(fakeJavaJAXRSCodegen.toApiName("$another-fake?"), "AnotherFakeApi"); + Assert.assertEquals(fakeJavaJAXRSCodegen.toApiName("fake_classname_tags 123#$%^"), "FakeClassnameTags123Api"); + } + + @Test + public void testInitialConfigValues() throws Exception { + final AbstractJavaJAXRSServerCodegen codegen = new P_AbstractJavaJAXRSServerCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertEquals(codegen.modelPackage(), "io.swagger.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "io.swagger.model"); + Assert.assertEquals(codegen.apiPackage(), "io.swagger.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "io.swagger.api"); + Assert.assertEquals(codegen.getInvokerPackage(), "io.swagger.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "io.swagger.api"); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final AbstractJavaJAXRSServerCodegen codegen = new P_AbstractJavaJAXRSServerCodegen(); + codegen.setHideGenerationTimestamp(true); + codegen.setModelPackage("xx.yyyyyyyy.model"); + codegen.setApiPackage("xx.yyyyyyyy.api"); + codegen.setInvokerPackage("xx.yyyyyyyy.invoker"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + 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.getInvokerPackage(), "xx.yyyyyyyy.invoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xx.yyyyyyyy.invoker"); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final AbstractJavaJAXRSServerCodegen codegen = new P_AbstractJavaJAXRSServerCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true"); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.mmmmm.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.aaaaa.api"); + codegen.additionalProperties().put(CodegenConstants.INVOKER_PACKAGE,"xyz.yyyyy.iiii.invoker"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + 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.getInvokerPackage(), "xyz.yyyyy.iiii.invoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.iiii.invoker"); + } + + private static class P_AbstractJavaJAXRSServerCodegen extends AbstractJavaJAXRSServerCodegen { + + @Override + public CodegenType getTag() { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public String getHelp() { + return null; + } + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/javascript/JavascriptClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/javascript/JavascriptClientCodegenTest.java new file mode 100644 index 000000000000..f329c3eb4b88 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/javascript/JavascriptClientCodegenTest.java @@ -0,0 +1,46 @@ +package org.openapitools.codegen.javascript; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.JavascriptClientCodegen; + +public class JavascriptClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final JavascriptClientCodegen codegen = new JavascriptClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertEquals(codegen.modelPackage(), "model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), null); + Assert.assertEquals(codegen.apiPackage(), "api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), null); + Assert.assertEquals(codegen.getInvokerPackage(), null); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), null); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final JavascriptClientCodegen codegen = new JavascriptClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final JavascriptClientCodegen codegen = new JavascriptClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/javascript/JavascriptClosureAngularClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/javascript/JavascriptClosureAngularClientCodegenTest.java new file mode 100644 index 000000000000..6d3e9a973eec --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/javascript/JavascriptClosureAngularClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.javascript; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.JavascriptClosureAngularClientCodegen; + +public class JavascriptClosureAngularClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final JavascriptClosureAngularClientCodegen codegen = new JavascriptClosureAngularClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final JavascriptClosureAngularClientCodegen codegen = new JavascriptClosureAngularClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final JavascriptClosureAngularClientCodegen codegen = new JavascriptClosureAngularClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/lua/LuaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/lua/LuaClientCodegenTest.java new file mode 100644 index 000000000000..7dbf38e72c0c --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/lua/LuaClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.lua; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.LuaClientCodegen; + +public class LuaClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final LuaClientCodegen codegen = new LuaClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final LuaClientCodegen codegen = new LuaClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final LuaClientCodegen codegen = new LuaClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/lumen/PhpLumenServerOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/lumen/PhpLumenServerOptionsTest.java new file mode 100644 index 000000000000..cf29430f578c --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/lumen/PhpLumenServerOptionsTest.java @@ -0,0 +1,51 @@ +package org.openapitools.codegen.lumen; + +import org.openapitools.codegen.AbstractOptionsTest; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.languages.PhpLumenServerCodegen; +import org.openapitools.codegen.options.PhpLumenServerOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class PhpLumenServerOptionsTest extends AbstractOptionsTest { + + @Tested + private PhpLumenServerCodegen clientCodegen; + + public PhpLumenServerOptionsTest() { + super(new PhpLumenServerOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(PhpLumenServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setParameterNamingConvention(PhpLumenServerOptionsProvider.VARIABLE_NAMING_CONVENTION_VALUE); + clientCodegen.setModelPackage(PhpLumenServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(PhpLumenServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + times = 1; + clientCodegen.setInvokerPackage(PhpLumenServerOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setPackagePath(PhpLumenServerOptionsProvider.PACKAGE_PATH_VALUE); + times = 1; + clientCodegen.setSrcBasePath(PhpLumenServerOptionsProvider.SRC_BASE_PATH_VALUE); + times = 1; + clientCodegen.setGitUserId(PhpLumenServerOptionsProvider.GIT_USER_ID_VALUE); + times = 1; + clientCodegen.setGitRepoId(PhpLumenServerOptionsProvider.GIT_REPO_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(PhpLumenServerOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + }}; + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/objc/ObjcClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/objc/ObjcClientCodegenTest.java new file mode 100644 index 000000000000..ebf4c3cf2a54 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/objc/ObjcClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.objc; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.ObjcClientCodegen; + +public class ObjcClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final ObjcClientCodegen codegen = new ObjcClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final ObjcClientCodegen codegen = new ObjcClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final ObjcClientCodegen codegen = new ObjcClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/objc/ObjcClientOptionsTest.java similarity index 100% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/objc/ObjcClientOptionsTest.java diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/objc/ObjcModelTest.java similarity index 72% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/objc/ObjcModelTest.java index b3c1ba888dd4..ef4f029900b6 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/objc/ObjcModelTest.java @@ -1,10 +1,18 @@ package org.openapitools.codegen.objc; -import org.openapitools.codegen.*; +import io.swagger.v3.oas.models.PathItem; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.languages.ObjcClientCodegen; -import io.swagger.models.*; -import io.swagger.models.properties.*; -import io.swagger.parser.SwaggerParser; + +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.parser.core.models.ParseOptions; +import io.swagger.v3.parser.util.SchemaTypeUtil; import com.google.common.collect.Sets; import org.testng.Assert; @@ -17,11 +25,11 @@ public class ObjcModelTest { @Test(description = "convert a model with a advanced map property") public void advancedMapPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new MapProperty().additionalProperties(new StringProperty()))) - .required("id"); + .addProperties("translations", new MapSchema() + .additionalProperties(new MapSchema().additionalProperties(new StringSchema()))) + .addRequiredItem("id"); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -42,14 +50,14 @@ public void advancedMapPropertyTest() { @Test(description = "convert a simple java model") public void simpleModelTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name") - .discriminator("test"); + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("name", new StringSchema()) + .addProperties("createdAt", new DateTimeSchema()) + .addRequiredItem("id") + .addRequiredItem("name") + .discriminator(new Discriminator().mapping("test", "test")); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -57,7 +65,7 @@ public void simpleModelTest() { Assert.assertEquals(cm.classname, "SWGSample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 3); - Assert.assertEquals(cm.discriminator,"test"); + Assert.assertEquals(cm.discriminator.getMapping().get("test"),"test"); final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "id"); @@ -94,12 +102,12 @@ public void simpleModelTest() { @Test(description = "convert a model with list property") public void listPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id"); + .addProperties("id", new IntegerSchema()) + .addProperties("urls", new ArraySchema() + .items(new StringSchema())) + .addRequiredItem("id"); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -134,11 +142,11 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + .addProperties("translations", new MapSchema() + .additionalProperties(new StringSchema())) + .addRequiredItem("id"); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -161,9 +169,9 @@ public void mapPropertyTest() { @Test(description = "convert a model with complex property") public void complexPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); + .addProperties("children", new Schema().$ref("#/definitions/Children")); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -183,10 +191,10 @@ public void complexPropertyTest() { @Test(description = "convert a model with complex list property") public void complexListPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); + .addProperties("children", new ArraySchema() + .items(new Schema().$ref("#/definitions/Children"))); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -208,10 +216,10 @@ public void complexListPropertyTest() { @Test(description = "convert a model with complex map property") public void complexMapPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); + .addProperties("children", new MapSchema() + .additionalProperties(new Schema().$ref("#/definitions/Children"))); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -235,9 +243,9 @@ public void complexMapPropertyTest() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Schema model = new ArraySchema() + .items(new Schema().$ref("#/definitions/Children")) + .description("an array model"); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -250,17 +258,17 @@ public void arrayModelTest() { Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("SWGChildren")).size(), 1); } - @Test(description = "convert an map model") + @Test(description = "convert an map model", enabled = false) public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Schema model = new Schema() + .description("a map model for testing ObjC generator") + .additionalProperties(new Schema().$ref("#/definitions/Children")); final DefaultCodegen codegen = new ObjcClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("map_model", model); - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "SWGSample"); - Assert.assertEquals(cm.description, "a map model"); + Assert.assertEquals(cm.name, "map_model"); + Assert.assertEquals(cm.classname, "SWGMapModel"); + Assert.assertEquals(cm.description, "a map model for testing ObjC generator"); Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.parent, "NSMutableDictionary"); Assert.assertEquals(cm.imports.size(), 1); @@ -269,11 +277,11 @@ public void mapModelTest() { @Test(description = "test udid") public void udidAndPasswordDataModelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final OpenAPI model = new OpenAPIParser().readLocation("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml", null, new ParseOptions()).getOpenAPI(); final DefaultCodegen codegen = new ObjcClientCodegen(); - final Model definition = model.getDefinitions().get("format_test"); + final Schema definition = model.getComponents().getSchemas().get("format_test"); - Property property = definition.getProperties().get("uuid"); + Schema property = ((Map) definition.getProperties()).get("uuid"); CodegenProperty prope = codegen.fromProperty("uuid", property); Assert.assertEquals(prope.baseType, "NSString"); @@ -283,20 +291,20 @@ public void udidAndPasswordDataModelTest() { @Test(description = "test mixedProperties") public void mixedPropertiesDataModelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final OpenAPI model = new OpenAPIParser().readLocation("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml", null, new ParseOptions()).getOpenAPI(); final DefaultCodegen codegen = new ObjcClientCodegen(); - final Model definition = model.getDefinitions().get("MixedPropertiesAndAdditionalPropertiesClass"); + final Schema definition = model.getComponents().getSchemas().get("MixedPropertiesAndAdditionalPropertiesClass"); - Property property = definition.getProperties().get("map"); + Schema property = ((Map)definition.getProperties()).get("map"); CodegenProperty prope = codegen.fromProperty("map", property); Assert.assertEquals(prope.baseType, "NSDictionary"); } @Test(description = "test isArrayModel") public void isArrayModelModelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final OpenAPI model = new OpenAPIParser().readLocation("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml", null, new ParseOptions()).getOpenAPI(); final DefaultCodegen codegen = new ObjcClientCodegen(); - final Model definition = model.getDefinitions().get("AnimalFarm"); + final Schema definition = model.getComponents().getSchemas().get("AnimalFarm"); final CodegenModel codegenModel = codegen.fromModel("AnimalFarm",definition); Assert.assertEquals(codegenModel.isArrayModel, true); @@ -304,39 +312,39 @@ public void isArrayModelModelTest() { } - @Test(description = "test binary data") + @Test(description = "test binary data", enabled = false) public void binaryDataModelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); + final OpenAPI model = new OpenAPIParser().readLocation("src/test/resources/2_0/binaryDataTest.json", null, new ParseOptions()).getOpenAPI(); final DefaultCodegen codegen = new ObjcClientCodegen(); final String path = "/tests/binaryResponse"; final Operation p = model.getPaths().get(path).getPost(); - final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); + final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getComponents().getSchemas()); - Assert.assertEquals(op.returnType, "NSData*"); - Assert.assertEquals(op.bodyParam.dataType, "NSData*"); Assert.assertTrue(op.bodyParam.isBinary); Assert.assertTrue(op.responses.get(0).isBinary); + Assert.assertEquals(op.returnType, "NSData*"); + Assert.assertEquals(op.bodyParam.dataType, "NSData*"); } @Test(description = "create proper imports per #316") public void issue316Test() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/postBodyTest.json"); + final OpenAPI model = new OpenAPIParser().readLocation("src/test/resources/2_0/postBodyTest.json", null, new ParseOptions()).getOpenAPI(); final DefaultCodegen codegen = new ObjcClientCodegen(); - final Map animalPaths = model.getPaths(); + final Map animalPaths = model.getPaths(); - final Path animalOps = animalPaths.get("/animals"); + final PathItem animalOps = animalPaths.get("/animals"); Assert.assertNotNull(animalOps.getPost()); - final CodegenOperation animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost(), model.getDefinitions()); + final CodegenOperation animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost(), model.getComponents().getSchemas()); Assert.assertEquals(animalCo.imports.size(), 1); Assert.assertTrue(animalCo.imports.contains("SWGAnimal")); - final Map insectPaths = model.getPaths(); - final Path insectOps = insectPaths.get("/insects"); + final Map insectPaths = model.getPaths(); + final PathItem insectOps = insectPaths.get("/insects"); Assert.assertNotNull(insectOps.getPost()); - final CodegenOperation insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost(), model.getDefinitions()); + final CodegenOperation insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost(), model.getComponents().getSchemas()); Assert.assertEquals(insectCo.imports.size(), 1); Assert.assertTrue(insectCo.imports.contains("SWGInsect")); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/BashClientOptionsProvider.java similarity index 93% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/BashClientOptionsProvider.java index f1316be3a80f..cfe57cc4ce17 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/BashClientOptionsProvider.java @@ -22,7 +22,7 @@ public class BashClientOptionsProvider implements OptionsProvider { = "PETSTORE_APIKEY"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - + public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @Override public String getLanguage() { @@ -52,6 +52,7 @@ public Map createOptions() { .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false") .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "false") .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) + .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartClientOptionsProvider.java similarity index 91% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartClientOptionsProvider.java index 01ebe4ea2755..e0ead7040546 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartClientOptionsProvider.java @@ -17,7 +17,7 @@ public class DartClientOptionsProvider implements OptionsProvider { public static final String SOURCE_FOLDER_VALUE = "src"; public static final String USE_ENUM_EXTENSION = "true"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - + public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @Override public String getLanguage() { @@ -36,6 +36,7 @@ public Map createOptions() { .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .put(DartClientCodegen.USE_ENUM_EXTENSION, USE_ENUM_EXTENSION) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) + .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/ElixirClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ElixirClientOptionsProvider.java similarity index 85% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/ElixirClientOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ElixirClientOptionsProvider.java index 73bbb1e70599..5669068e750c 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/ElixirClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ElixirClientOptionsProvider.java @@ -7,6 +7,7 @@ public class ElixirClientOptionsProvider implements OptionsProvider { public static final String INVOKER_PACKAGE_VALUE = "Yay.Pets"; + public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @Override public String getLanguage() { @@ -23,6 +24,7 @@ public Map createOptions() { .put(CodegenConstants.INVOKER_PACKAGE, "Yay.Pets") .put("licenseHeader", "# Copyright 2017 Me\n#\n# Licensed under the Apache License") .put(CodegenConstants.PACKAGE_NAME, "yay_pets") + .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/GoClientOptionsProvider.java similarity index 87% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/GoClientOptionsProvider.java index a97de5795a45..f95e15df7d7e 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/GoClientOptionsProvider.java @@ -12,6 +12,7 @@ public class GoClientOptionsProvider implements OptionsProvider { public static final String PACKAGE_VERSION_VALUE = "1.0.0"; public static final String PACKAGE_NAME_VALUE = "Go"; public static final boolean WITH_XML_VALUE = true; + public static final Boolean PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = true; @Override public String getLanguage() { @@ -26,6 +27,7 @@ public Map createOptions() { .put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .put(CodegenConstants.WITH_XML, "true") + .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, "true") .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/GoServerOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/GoServerOptionsProvider.java similarity index 87% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/GoServerOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/GoServerOptionsProvider.java index b2d242f90480..35bb7467d546 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/GoServerOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/GoServerOptionsProvider.java @@ -10,7 +10,7 @@ public class GoServerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; 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"; @Override public String getLanguage() { @@ -23,6 +23,7 @@ public Map createOptions() { return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .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, "true") .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/HaskellServantOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/HaskellServantOptionsProvider.java similarity index 84% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/HaskellServantOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/HaskellServantOptionsProvider.java index 69ff4f3b3b8f..f118e0fde6b5 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/HaskellServantOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/HaskellServantOptionsProvider.java @@ -1,6 +1,7 @@ package org.openapitools.codegen.options; import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.HaskellServantCodegen; import com.google.common.collect.ImmutableMap; @@ -12,7 +13,7 @@ public class HaskellServantOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; 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"; @Override public String getLanguage() { @@ -27,6 +28,7 @@ public Map createOptions() { .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .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) .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ObjcClientOptionsProvider.java similarity index 100% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ObjcClientOptionsProvider.java diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/OptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/OptionsProvider.java similarity index 100% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/OptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/OptionsProvider.java diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PerlClientOptionsProvider.java similarity index 85% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PerlClientOptionsProvider.java index 89b1ec036d14..09283b992591 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PerlClientOptionsProvider.java @@ -1,7 +1,6 @@ package org.openapitools.codegen.options; import org.openapitools.codegen.CodegenConstants; - import org.openapitools.codegen.languages.PerlClientCodegen; import com.google.common.collect.ImmutableMap; @@ -11,6 +10,7 @@ public class PerlClientOptionsProvider implements OptionsProvider { public static final String MODULE_NAME_VALUE = ""; public static final String MODULE_VERSION_VALUE = ""; + public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @Override public String getLanguage() { @@ -25,6 +25,7 @@ public Map createOptions() { .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "true") .put("hideGenerationTimestamp", "true") + .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpClientOptionsProvider.java similarity index 93% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpClientOptionsProvider.java index 4b36c332768c..ae98cebc877e 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpClientOptionsProvider.java @@ -22,7 +22,7 @@ public class PhpClientOptionsProvider implements OptionsProvider { public static final String GIT_REPO_ID_VALUE = "git-swagger-client-php"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - + public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @Override public String getLanguage() { @@ -47,6 +47,7 @@ public Map createOptions() { .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) + .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpLumenServerOptionsProvider.java similarity index 88% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpLumenServerOptionsProvider.java index 3beafacd974e..3ec1980c3e7f 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpLumenServerOptionsProvider.java @@ -7,7 +7,7 @@ import java.util.Map; -public class LumenServerOptionsProvider implements OptionsProvider { +public class PhpLumenServerOptionsProvider implements OptionsProvider { public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; @@ -20,11 +20,11 @@ public class LumenServerOptionsProvider implements OptionsProvider { public static final String GIT_REPO_ID_VALUE = "git-swagger-php"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - + public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @Override public String getLanguage() { - return "lumen"; + return "php-lumen"; } @Override @@ -42,6 +42,7 @@ public Map createOptions() { .put(CodegenConstants.GIT_REPO_ID, GIT_REPO_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) + .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SilexServerOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSilexServerOptionsProvider.java similarity index 77% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/SilexServerOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSilexServerOptionsProvider.java index 5533b0787faf..9ef424f66808 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SilexServerOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSilexServerOptionsProvider.java @@ -6,14 +6,15 @@ import java.util.Map; -public class SilexServerOptionsProvider implements OptionsProvider { +public class PhpSilexServerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; 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"; @Override public String getLanguage() { - return "silex-PHP"; + return "php-silex"; } @Override @@ -22,6 +23,7 @@ public Map createOptions() { return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .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) .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SlimFrameworkServerOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlimServerOptionsProvider.java similarity index 79% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/SlimFrameworkServerOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlimServerOptionsProvider.java index a64d039be28f..d2aa3302d78c 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SlimFrameworkServerOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlimServerOptionsProvider.java @@ -6,11 +6,11 @@ import java.util.Map; -public class SlimFrameworkServerOptionsProvider implements OptionsProvider { +public class PhpSlimServerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; 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"; @Override public String getLanguage() { @@ -23,6 +23,7 @@ public Map createOptions() { return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .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) .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonClientOptionsProvider.java similarity index 100% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonClientOptionsProvider.java diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java similarity index 93% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java index 7ea0ebfd88d2..51c6ae49cc64 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java @@ -21,7 +21,7 @@ public class RubyClientOptionsProvider implements OptionsProvider { public static final String GEM_AUTHOR_VALUE = "foo"; public static final String GEM_AUTHOR_EMAIL_VALUE = "foo"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - + public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @Override public String getLanguage() { @@ -45,6 +45,7 @@ public Map createOptions() { .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) + .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) .build(); } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SinatraServerOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubySinatraServerOptionsProvider.java similarity index 80% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/SinatraServerOptionsProvider.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubySinatraServerOptionsProvider.java index 7e0e078a70ae..e03e30e997b6 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/SinatraServerOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubySinatraServerOptionsProvider.java @@ -4,10 +4,10 @@ import java.util.Map; -public class SinatraServerOptionsProvider implements OptionsProvider { +public class RubySinatraServerOptionsProvider implements OptionsProvider { @Override public String getLanguage() { - return "sinatra"; + return "ruby-sinatra"; } @Override diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/perl/PerlClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/perl/PerlClientCodegenTest.java new file mode 100644 index 000000000000..1619a73fa547 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/perl/PerlClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.perl; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.PerlClientCodegen; + +public class PerlClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final PerlClientCodegen codegen = new PerlClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final PerlClientCodegen codegen = new PerlClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final PerlClientCodegen codegen = new PerlClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/perl/PerlClientOptionsTest.java similarity index 86% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/perl/PerlClientOptionsTest.java index b72737a8c879..a6c7c05d168f 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/perl/PerlClientOptionsTest.java @@ -30,6 +30,8 @@ protected void setExpectations() { times = 1; clientCodegen.setModuleVersion(PerlClientOptionsProvider.MODULE_VERSION_VALUE); times = 1; + clientCodegen.setPrependFormOrBodyParameters(Boolean.valueOf(PerlClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); + times = 1; }}; } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/AbstractPhpCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/AbstractPhpCodegenTest.java new file mode 100644 index 000000000000..7494cc688232 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/AbstractPhpCodegenTest.java @@ -0,0 +1,81 @@ +package org.openapitools.codegen.php; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.languages.AbstractPhpCodegen; + +public class AbstractPhpCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final AbstractPhpCodegen codegen = new P_AbstractPhpCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertEquals(codegen.modelPackage(), "php\\Model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "php\\Model"); + Assert.assertEquals(codegen.apiPackage(), "php\\Api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "php\\Api"); + Assert.assertEquals(codegen.getInvokerPackage(), "php"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "php"); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final AbstractPhpCodegen codegen = new P_AbstractPhpCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.setModelPackage("My\\Client\\Model"); + codegen.setApiPackage("My\\Client\\Api"); + codegen.setInvokerPackage("My\\Client\\Invoker"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertEquals(codegen.modelPackage(), "My\\Client\\Model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "My\\Client\\Model"); + Assert.assertEquals(codegen.apiPackage(), "My\\Client\\Api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE),"My\\Client\\Api"); + Assert.assertEquals(codegen.getInvokerPackage(), "My\\Client\\Invoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "My\\Client\\Invoker"); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final AbstractPhpCodegen codegen = new P_AbstractPhpCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "PHPmodel"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "PHPapi"); + codegen.additionalProperties().put(CodegenConstants.INVOKER_PACKAGE, "PHPinvoker"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertEquals(codegen.modelPackage(), "PHPmodel"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "PHPmodel"); + Assert.assertEquals(codegen.apiPackage(), "PHPapi"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "PHPapi"); + Assert.assertEquals(codegen.getInvokerPackage(), "PHPinvoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "PHPinvoker"); + } + + private static class P_AbstractPhpCodegen extends AbstractPhpCodegen { + @Override + public CodegenType getTag() { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public String getHelp() { + return null; + } + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpClientCodegenTest.java new file mode 100644 index 000000000000..8d2a02a503d5 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpClientCodegenTest.java @@ -0,0 +1,63 @@ +package org.openapitools.codegen.php; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.PhpClientCodegen; + +public class PhpClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final PhpClientCodegen codegen = new PhpClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertEquals(codegen.modelPackage(), "Swagger\\Client\\Model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "Swagger\\Client\\Model"); + Assert.assertEquals(codegen.apiPackage(), "Swagger\\Client\\Api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "Swagger\\Client\\Api"); + Assert.assertEquals(codegen.getInvokerPackage(), "Swagger\\Client"); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final PhpClientCodegen codegen = new PhpClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.setModelPackage("My\\Client\\Model"); + codegen.setApiPackage("My\\Client\\Api"); + codegen.setInvokerPackage("My\\Client\\Invoker"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertEquals(codegen.modelPackage(), "My\\Client\\Model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "My\\Client\\Model"); + Assert.assertEquals(codegen.apiPackage(), "My\\Client\\Api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE),"My\\Client\\Api"); + Assert.assertEquals(codegen.getInvokerPackage(), "My\\Client\\Invoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "My\\Client\\Invoker"); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final PhpClientCodegen codegen = new PhpClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "Xmodel"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "Xapi"); + codegen.additionalProperties().put(CodegenConstants.INVOKER_PACKAGE, "Xinvoker"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertEquals(codegen.modelPackage(), "Xinvoker\\Xmodel"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "Xinvoker\\Xmodel"); + Assert.assertEquals(codegen.apiPackage(), "Xinvoker\\Xapi"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "Xinvoker\\Xapi"); + Assert.assertEquals(codegen.getInvokerPackage(), "Xinvoker"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "Xinvoker"); + } + +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/php/PhpClientExampleTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpClientExampleTest.java similarity index 100% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/php/PhpClientExampleTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpClientExampleTest.java diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpClientOptionsTest.java similarity index 100% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpClientOptionsTest.java diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/php/PhpModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpModelTest.java similarity index 81% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/php/PhpModelTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpModelTest.java index babd9037a940..abb8d9f6c31b 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/php/PhpModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpModelTest.java @@ -5,42 +5,37 @@ import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.languages.PhpClientCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Operation; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; - -import java.util.ArrayList; + +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.parser.core.models.ParseOptions; + import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import com.google.common.collect.Sets; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + @SuppressWarnings("static-method") public class PhpModelTest { + protected static final Logger LOGGER = LoggerFactory.getLogger(PhpModelTest.class); @Test(description = "convert a simple php model") public void simpleModelTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); + .addProperties("id", new IntegerSchema()) + .addProperties("name", new StringSchema()) + .addProperties("createdAt", new DateTimeSchema()) + .addRequiredItem("id") + .addRequiredItem("name"); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -87,12 +82,12 @@ public void simpleModelTest() { @Test(description = "convert a model with list property") public void listPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id"); + .addProperties("id", new IntegerSchema()) + .addProperties("urls", new ArraySchema() + .items(new StringSchema())) + .addRequiredItem("id"); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -126,11 +121,11 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + .addProperties("translations", new MapSchema() + .additionalProperties(new StringSchema())) + .addRequiredItem("id"); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -152,9 +147,9 @@ public void mapPropertyTest() { @Test(description = "convert a model with complex property") public void complexPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); + .addProperties("children", new Schema().$ref("#/definitions/Children")); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -174,10 +169,10 @@ public void complexPropertyTest() { @Test(description = "convert a model with complex list property") public void complexListProperty() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); + .addProperties("children", new ArraySchema() + .items(new Schema().$ref("#/definitions/Children"))); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -197,11 +192,11 @@ public void complexListProperty() { } @Test(description = "convert a model with complex map property") - public void complexMapProperty() { - final Model model = new ModelImpl() + public void complexMapSchema() { + final Schema model = new Schema() .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); + .addProperties("children", new MapSchema() + .additionalProperties(new Schema().$ref("#/definitions/Children"))); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -226,14 +221,17 @@ public void complexMapProperty() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Schema model = new ArraySchema() + .items(new Schema().$ref("#/definitions/Children")) + .description("an array model"); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); + Assert.assertEquals(model.getDescription(), "an array model"); + Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); + Assert.assertTrue(cm.isArrayModel); Assert.assertEquals(cm.description, "an array model"); Assert.assertEquals(cm.vars.size(), 0); // skip import test as import is not used by PHP codegen @@ -241,9 +239,9 @@ public void arrayModelTest() { @Test(description = "convert an map model") public void mapModelTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + .additionalProperties(new Schema().$ref("#/definitions/Children")); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -271,7 +269,7 @@ public static Object[][] primeNumbers() { @Test(dataProvider = "modelNames", description = "avoid inner class") public void modelNameTest(String name, String expectedName) { - final Model model = new ModelImpl(); + final Schema model = new Schema(); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel(name, model); @@ -280,12 +278,13 @@ public void modelNameTest(String name, String expectedName) { } @Test(description = "test enum array model") - public void enumArrayMdoelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + public void enumArrayModelTest() { + final OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml", null, new ParseOptions()).getOpenAPI(); final DefaultCodegen codegen = new PhpClientCodegen(); - final Model definition = model.getDefinitions().get("EnumArrays"); + final Map schemas = openAPI.getComponents().getSchemas(); + final Schema definition = schemas.get("EnumArrays"); - Property property = definition.getProperties().get("array_enum"); + Schema property = (Schema) definition.getProperties().get("array_enum"); CodegenProperty prope = codegen.fromProperty("array_enum", property); codegen.updateCodegenPropertyEnum(prope); Assert.assertEquals(prope.datatypeWithEnum, "ARRAY_ENUM[]"); @@ -312,11 +311,11 @@ public void enumArrayMdoelTest() { @Test(description = "test enum model for values (numeric, string, etc)") public void enumMdoelValueTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml", null, new ParseOptions()).getOpenAPI(); final DefaultCodegen codegen = new PhpClientCodegen(); - final Model definition = model.getDefinitions().get("Enum_Test"); + final Schema definition = openAPI.getComponents().getSchemas().get("Enum_Test"); - Property property = definition.getProperties().get("enum_integer"); + Schema property = (Schema) definition.getProperties().get("enum_integer"); CodegenProperty prope = codegen.fromProperty("enum_integer", property); codegen.updateCodegenPropertyEnum(prope); Assert.assertEquals(prope.datatypeWithEnum, "ENUM_INTEGER"); @@ -333,7 +332,6 @@ public void enumMdoelValueTest() { minusOne.put("name", "MINUS_1"); minusOne.put("value", "-1"); Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(one, minusOne)); - } @Test(description = "test enum variable names for reserved words") @@ -346,15 +344,16 @@ public void testReservedWord() throws Exception { Assert.assertEquals(codegen.toEnumVarName("hello", null), "HELLO"); } + // datetime (or primitive type) not yet supported in HTTP request body @Test(description = "returns DateTime when using `--model-name-prefix`") public void dateTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/datePropertyTest.json"); + final OpenAPI model = new OpenAPIParser().readLocation("src/test/resources/2_0/datePropertyTest.json", null, new ParseOptions()).getOpenAPI(); final DefaultCodegen codegen = new PhpClientCodegen(); codegen.setModelNamePrefix("foo"); final String path = "/tests/dateResponse"; final Operation p = model.getPaths().get(path).getPost(); - final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); + final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getComponents().getSchemas()); Assert.assertEquals(op.returnType, "\\DateTime"); Assert.assertEquals(op.bodyParam.dataType, "\\DateTime"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpSymfonyServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpSymfonyServerCodegenTest.java new file mode 100644 index 000000000000..6a5db7ed27f1 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpSymfonyServerCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.php; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.PhpSymfonyServerCodegen; + +public class PhpSymfonyServerCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final PhpSymfonyServerCodegen codegen = new PhpSymfonyServerCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final PhpSymfonyServerCodegen codegen = new PhpSymfonyServerCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final PhpSymfonyServerCodegen codegen = new PhpSymfonyServerCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientCodegenTest.java new file mode 100644 index 000000000000..447bd0bb14d0 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.python; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.PythonClientCodegen; + +public class PythonClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final PythonClientCodegen codegen = new PythonClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final PythonClientCodegen codegen = new PythonClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final PythonClientCodegen codegen = new PythonClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientOptionsTest.java similarity index 100% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientOptionsTest.java diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/python/PythonTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonTest.java similarity index 81% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/python/PythonTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonTest.java index ef9483fb3525..5543a8c53205 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/python/PythonTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonTest.java @@ -5,62 +5,55 @@ import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.languages.PythonClientCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Operation; -import io.swagger.models.Swagger; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; -import io.swagger.parser.SwaggerParser; + +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.parser.core.models.ParseOptions; +import io.swagger.v3.parser.util.SchemaTypeUtil; import org.testng.Assert; import org.testng.annotations.Test; -import org.testng.annotations.ITestAnnotation; import com.google.common.collect.Sets; -import java.util.Map; @SuppressWarnings("static-method") public class PythonTest { @Test(description = "convert a python model with dots") public void modelTest() { - final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/v1beta3.json"); + final OpenAPI openAPI= new OpenAPIParser().readLocation("src/test/resources/2_0/v1beta3.json", null, new ParseOptions()).getOpenAPI(); final DefaultCodegen codegen = new PythonClientCodegen(); - final CodegenModel simpleName = codegen.fromModel("v1beta3.Binding", swagger.getDefinitions().get("v1beta3.Binding")); + final CodegenModel simpleName = codegen.fromModel("v1beta3.Binding", openAPI.getComponents().getSchemas().get("v1beta3.Binding")); Assert.assertEquals(simpleName.name, "v1beta3.Binding"); Assert.assertEquals(simpleName.classname, "V1beta3Binding"); Assert.assertEquals(simpleName.classVarName, "v1beta3_binding"); - final CodegenModel compoundName = codegen.fromModel("v1beta3.ComponentStatus", swagger.getDefinitions().get("v1beta3.ComponentStatus")); + final CodegenModel compoundName = codegen.fromModel("v1beta3.ComponentStatus", openAPI.getComponents().getSchemas().get("v1beta3.ComponentStatus")); Assert.assertEquals(compoundName.name, "v1beta3.ComponentStatus"); Assert.assertEquals(compoundName.classname, "V1beta3ComponentStatus"); Assert.assertEquals(compoundName.classVarName, "v1beta3_component_status"); final String path = "/api/v1beta3/namespaces/{namespaces}/bindings"; - final Operation operation = swagger.getPaths().get(path).getPost(); - final CodegenOperation codegenOperation = codegen.fromOperation(path, "get", operation, swagger.getDefinitions()); + final Operation operation = openAPI.getPaths().get(path).getPost(); + final CodegenOperation codegenOperation = codegen.fromOperation(path, "get", operation, openAPI.getComponents().getSchemas()); Assert.assertEquals(codegenOperation.returnType, "V1beta3Binding"); Assert.assertEquals(codegenOperation.returnBaseType, "V1beta3Binding"); } @Test(description = "convert a simple java model") public void simpleModelTest() { - final Model model = new ModelImpl() + final Schema schema = new Schema() .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("name", new StringSchema()) + .addProperties("createdAt", new DateTimeSchema()) + .addRequiredItem("id") + .addRequiredItem("name"); final DefaultCodegen codegen = new PythonClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); + final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); @@ -102,12 +95,12 @@ public void simpleModelTest() { @Test(description = "convert a model with list property") public void listPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id"); + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("urls", new ArraySchema() + .items(new StringSchema())) + .addRequiredItem("id"); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -142,11 +135,11 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + .addProperties("translations", new MapSchema() + .additionalProperties(new StringSchema())) + .addRequiredItem("id"); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -168,9 +161,9 @@ public void mapPropertyTest() { @Test(description = "convert a model with complex property") public void complexPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); + .addProperties("children", new Schema().$ref("#/definitions/Children")); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -190,10 +183,10 @@ public void complexPropertyTest() { @Test(description = "convert a model with complex list property") public void complexListPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); + .addProperties("children", new ArraySchema() + .items(new Schema().$ref("#/definitions/Children"))); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -215,10 +208,10 @@ public void complexListPropertyTest() { @Test(description = "convert a model with complex map property") public void complexMapPropertyTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); + .addProperties("children", new MapSchema() + .additionalProperties(new Schema().$ref("#/definitions/Children"))); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -244,9 +237,10 @@ public void complexMapPropertyTest() { // should not start with 'null'. need help from the community to investigate further @Test(enabled = false, description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Schema model = new ArraySchema() + //.description() + .items(new Schema().$ref("#/definitions/Children")) + .description("an array model"); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -262,9 +256,9 @@ public void arrayModelTest() { // should not start with 'null'. need help from the community to investigate further @Test(enabled = false, description = "convert an map model") public void mapModelTest() { - final Model model = new ModelImpl() + final Schema model = new Schema() .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + .additionalProperties(new Schema().$ref("#/definitions/Children")); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/r/RClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/r/RClientCodegenTest.java new file mode 100644 index 000000000000..1dffe667109a --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/r/RClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.r; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.RClientCodegen; + +public class RClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final RClientCodegen codegen = new RClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final RClientCodegen codegen = new RClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final RClientCodegen codegen = new RClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} 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 new file mode 100644 index 000000000000..13e908dd3b92 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientCodegenTest.java @@ -0,0 +1,105 @@ +package org.openapitools.codegen.ruby; + +import org.openapitools.codegen.ClientOpts; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.languages.RubyClientCodegen; + +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.parser.core.models.ParseOptions; + +import org.apache.commons.io.FileUtils; +import org.junit.rules.TemporaryFolder; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.util.List; + +import static org.testng.Assert.*; + +/** + * Tests for RubyClientCodegen-generated templates + */ +public class RubyClientCodegenTest { + + public TemporaryFolder folder = new TemporaryFolder(); + + @BeforeMethod + public void setUp() throws Exception { + folder.create(); + } + + @AfterMethod + public void tearDown() throws Exception { + folder.delete(); + } + + @Test + public void testGenerateRubyClientWithHtmlEntity() throws Exception { + final File output = folder.getRoot(); + + final OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/2_0/pathWithHtmlEntity.yaml", null, new ParseOptions()).getOpenAPI(); + CodegenConfig codegenConfig = new RubyClientCodegen(); + codegenConfig.setOutputDir(output.getAbsolutePath()); + + ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).openAPI(openAPI).config(codegenConfig); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + boolean apiFileGenerated = false; + for (File file : files) { + if (file.getName().equals("default_api.rb")) { + apiFileGenerated = true; + // Ruby client should set the path unescaped in the api file + assertTrue(FileUtils.readFileToString(file, StandardCharsets.UTF_8).contains("local_var_path = '/foo=bar'")); + } + } + if (!apiFileGenerated) { + fail("Default api file is not generated!"); + } + } + + @Test + public void testInitialConfigValues() throws Exception { + final RubyClientCodegen codegen = new RubyClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertEquals(codegen.modelPackage(), "models"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), null); + Assert.assertEquals(codegen.apiPackage(), "api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), null); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final RubyClientCodegen codegen = new RubyClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final RubyClientCodegen codegen = new RubyClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "ruby-models"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "ruby-api"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "ruby-models"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "ruby-api"); + } +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientOptionsTest.java similarity index 100% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientOptionsTest.java diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/rubysinatra/RubySinatraServerOptionsTest.java similarity index 50% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/rubysinatra/RubySinatraServerOptionsTest.java index 3f906bd8c3fa..29f6a67dfca2 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/rubysinatra/RubySinatraServerOptionsTest.java @@ -1,20 +1,20 @@ -package org.openapitools.codegen.sinatra; +package org.openapitools.codegen.rubysinatra; import org.openapitools.codegen.AbstractOptionsTest; import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.SinatraServerCodegen; -import org.openapitools.codegen.options.SinatraServerOptionsProvider; +import org.openapitools.codegen.languages.RubySinatraServerCodegen; +import org.openapitools.codegen.options.RubySinatraServerOptionsProvider; import mockit.Expectations; import mockit.Tested; -public class SinatraServerOptionsTest extends AbstractOptionsTest { +public class RubySinatraServerOptionsTest extends AbstractOptionsTest { @Tested - private SinatraServerCodegen clientCodegen; + private RubySinatraServerCodegen clientCodegen; - public SinatraServerOptionsTest() { - super(new SinatraServerOptionsProvider()); + public RubySinatraServerOptionsTest() { + super(new RubySinatraServerOptionsProvider()); } @Override diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/rust/RustClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/rust/RustClientCodegenTest.java new file mode 100644 index 000000000000..9b6b1aec9802 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/rust/RustClientCodegenTest.java @@ -0,0 +1,40 @@ +package org.openapitools.codegen.rust; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.RustClientCodegen; + +public class RustClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final RustClientCodegen codegen = new RustClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final RustClientCodegen codegen = new RustClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final RustClientCodegen codegen = new RustClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/silex/PhpSilexServerOptionsTest.java similarity index 57% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/silex/PhpSilexServerOptionsTest.java index 3f8ac24de59e..c453d1a4ab1b 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/silex/PhpSilexServerOptionsTest.java @@ -2,19 +2,19 @@ import org.openapitools.codegen.AbstractOptionsTest; import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.SilexServerCodegen; -import org.openapitools.codegen.options.SilexServerOptionsProvider; +import org.openapitools.codegen.languages.PhpSilexServerCodegen; +import org.openapitools.codegen.options.PhpSilexServerOptionsProvider; import mockit.Expectations; import mockit.Tested; -public class SilexServerOptionsTest extends AbstractOptionsTest { +public class PhpSilexServerOptionsTest extends AbstractOptionsTest { @Tested - private SilexServerCodegen clientCodegen; + private PhpSilexServerCodegen clientCodegen; - public SilexServerOptionsTest() { - super(new SilexServerOptionsProvider()); + public PhpSilexServerOptionsTest() { + super(new PhpSilexServerOptionsProvider()); } @Override @@ -26,7 +26,7 @@ protected CodegenConfig getCodegenConfig() { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SilexServerOptionsProvider.SORT_PARAMS_VALUE)); + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(PhpSilexServerOptionsProvider.SORT_PARAMS_VALUE)); times = 1; }}; } diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerOptionsTest.java similarity index 55% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java rename to modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerOptionsTest.java index 6e2e06e3a67e..4730fceae2b5 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerOptionsTest.java @@ -2,19 +2,19 @@ import org.openapitools.codegen.AbstractOptionsTest; import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.SlimFrameworkServerCodegen; -import org.openapitools.codegen.options.SlimFrameworkServerOptionsProvider; +import org.openapitools.codegen.languages.PhpSlimServerCodegen; +import org.openapitools.codegen.options.PhpSlimServerOptionsProvider; import mockit.Expectations; import mockit.Tested; -public class SlimFrameworkServerOptionsTest extends AbstractOptionsTest { +public class PhpSlimServerOptionsTest extends AbstractOptionsTest { @Tested - private SlimFrameworkServerCodegen clientCodegen; + private PhpSlimServerCodegen clientCodegen; - public SlimFrameworkServerOptionsTest() { - super(new SlimFrameworkServerOptionsProvider()); + public PhpSlimServerOptionsTest() { + super(new PhpSlimServerOptionsProvider()); } @Override @@ -26,7 +26,7 @@ protected CodegenConfig getCodegenConfig() { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SlimFrameworkServerOptionsProvider.SORT_PARAMS_VALUE)); + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(PhpSlimServerOptionsProvider.SORT_PARAMS_VALUE)); times = 1; }}; } diff --git a/modules/openapi-generator/src/test/resources/2_0/long_description_issue_7839.json b/modules/openapi-generator/src/test/resources/2_0/long_description_issue_7839.json new file mode 100644 index 000000000000..62bbf0059f34 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/2_0/long_description_issue_7839.json @@ -0,0 +1,813 @@ +{ + "swagger" : "2.0", + "info" : { + "description" : "Are creatures of the cosmos Rig Veda? Trillion! Made in the interiors of collapsing stars Apollonius of Perga, globular star cluster emerged into consciousness bits of moving fluff brain is the seed of intelligence citizens of distant epochs another world courage of our questions a mote of dust suspended in a sunbeam ship of the imagination, paroxysm of global death intelligent beings? Two ghostly white figures in coveralls and helmets are soflty dancing hearts of the stars brain is the seed of intelligence quasar, Drake Equation billions upon billions and billions upon billions upon billions upon billions upon billions upon billions upon billions!\n", + "version" : "1.0.0", + "title" : "Swagger Petstore", + "termsOfService" : "http://swagger.io/terms/", + "contact" : { + "email" : "apiteam@swagger.io" + }, + "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" : "Light years, culture, dispassionate extraterrestrial observer citizens of distant epochs intelligent beings Jean-Francois Champollion encyclopaedia galactica Sea of Tranquility emerged into consciousness Cambrian explosion another world Cambrian explosion globular star cluster. Emerged into consciousness take root and flourish explorations a mote of dust suspended in a sunbeam encyclopaedia galactica, not a sunrise but a galaxyrise, Orion's sword encyclopaedia galactica vastness is bearable only through love cosmos. Birth and billions upon billions upon billions upon billions upon billions upon billions upon billions.", + "externalDocs" : { + "description" : "Find out more", + "url" : "http://swagger.io" + } + }, { + "name" : "store", + "description" : "Access to Petstore orders" + }, { + "name" : "user", + "description" : "Operations about user", + "externalDocs" : { + "description" : "Find out more about our store", + "url" : "http://swagger.io" + } + } ], + "schemes" : [ "http" ], + "paths" : { + "/pet" : { + "post" : { + "tags" : [ "pet" ], + "summary" : "Add a new pet to the store", + "operationId" : "addPet", + "consumes" : [ "application/json", "application/xml" ], + "produces" : [ "application/json", "application/xml" ], + "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", + "operationId" : "updatePet", + "consumes" : [ "application/json", "application/xml" ], + "produces" : [ "application/json", "application/xml" ], + "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/json", "application/xml" ], + "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" : "multi" + } ], + "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" : "Muliple tags can be provided with comma separated strings. Use\\ \\ tag1, tag2, tag3 for testing.", + "operationId" : "findPetsByTags", + "produces" : [ "application/json", "application/xml" ], + "parameters" : [ { + "name" : "tags", + "in" : "query", + "description" : "Tags to filter by", + "required" : true, + "type" : "array", + "items" : { + "type" : "string" + }, + "collectionFormat" : "multi" + } ], + "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/json", "application/xml" ], + "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", + "operationId" : "updatePetWithForm", + "consumes" : [ "application/x-www-form-urlencoded" ], + "produces" : [ "application/json", "application/xml" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet that needs to be updated", + "required" : true, + "type" : "integer", + "format" : "int64" + }, { + "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" + } ], + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + }, + "delete" : { + "tags" : [ "pet" ], + "summary" : "Deletes a pet", + "operationId" : "deletePet", + "produces" : [ "application/json", "application/xml" ], + "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 ID supplied" + }, + "404" : { + "description" : "Pet not found" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/pet/{petId}/uploadImage" : { + "post" : { + "tags" : [ "pet" ], + "summary" : "uploads an image", + "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", + "operationId" : "placeOrder", + "produces" : [ "application/json", "application/xml" ], + "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 >= 1 and <= 10.\\ \\ Other values will generated exceptions", + "operationId" : "getOrderById", + "produces" : [ "application/json", "application/xml" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of pet that needs to be fetched", + "required" : true, + "type" : "integer", + "maximum" : 10.0, + "minimum" : 1.0, + "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 positive integer value.\\ \\ Negative or non-integer values will generate API errors", + "operationId" : "deleteOrder", + "produces" : [ "application/json", "application/xml" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of the order that needs to be deleted", + "required" : true, + "type" : "integer", + "minimum" : 1.0, + "format" : "int64" + } ], + "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/json", "application/xml" ], + "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", + "operationId" : "createUsersWithArrayInput", + "produces" : [ "application/json", "application/xml" ], + "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", + "operationId" : "createUsersWithListInput", + "produces" : [ "application/json", "application/xml" ], + "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", + "operationId" : "loginUser", + "produces" : [ "application/json", "application/xml" ], + "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 token expires" + } + } + }, + "400" : { + "description" : "Invalid username/password supplied" + } + } + } + }, + "/user/logout" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Logs out current logged in user session", + "operationId" : "logoutUser", + "produces" : [ "application/json", "application/xml" ], + "parameters" : [ ], + "responses" : { + "default" : { + "description" : "successful operation" + } + } + } + }, + "/user/{username}" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Get user by user name", + "operationId" : "getUserByName", + "produces" : [ "application/json", "application/xml" ], + "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/json", "application/xml" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "name that need to be updated", + "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/json", "application/xml" ], + "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/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" : { + "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" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "xml" : { + "name" : "Category" + } + }, + "User" : { + "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" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "type" : "object", + "required" : [ "name", "photoUrls" ], + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "category" : { + "$ref" : "#/definitions/Category" + }, + "name" : { + "type" : "string", + "example" : "doggie" + }, + "photoUrls" : { + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + }, + "items" : { + "type" : "string" + } + }, + "tags" : { + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + }, + "items" : { + "$ref" : "#/definitions/Tag" + } + }, + "status" : { + "type" : "string", + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ] + } + }, + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "type" : "object", + "properties" : { + "code" : { + "type" : "integer", + "format" : "int32" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + } + } + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/2_0/pathWithHtmlEntity.yaml b/modules/openapi-generator/src/test/resources/2_0/pathWithHtmlEntity.yaml index 929a5cd8f9b5..cf5fe1d5100e 100644 --- a/modules/openapi-generator/src/test/resources/2_0/pathWithHtmlEntity.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/pathWithHtmlEntity.yaml @@ -1,10 +1,18 @@ ---- +--- swagger: "2.0" -basePath: "/" -paths: - /foo=bar: - get: - parameters: [] - responses: - 200: - description: "success" +basePath: / +info: + description: "Test for response code default" + title: "path with html entity test" + version: "1.0.0" +paths: + /foo=bar: + get: + produces: + - application/json + responses: + 200: + description: "successful operation" + default: + description: "Internal server error" + summary: Test diff --git a/modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index bf15aa2900f5..71452db456d4 100644 --- a/modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -471,7 +471,7 @@ paths: X-Expires-After: type: string format: date-time - description: date in UTC when toekn expires + description: date in UTC when token expires '400': description: Invalid username/password supplied /user/logout: @@ -615,9 +615,7 @@ paths: description: To test enum parameters operationId: testEnumParameters consumes: - - "*/*" - produces: - - "*/*" + - "application/x-www-form-urlencoded" parameters: - name: enum_form_string_array type: array @@ -690,7 +688,7 @@ paths: enum: - 1.1 - -1.2 - in: formData + in: query description: Query parameter enum test (double) responses: '400': @@ -712,11 +710,7 @@ paths: 가짜 엔드 포인트 operationId: testEndpointParameters consumes: - - application/xml; charset=utf-8 - - application/json; charset=utf-8 - produces: - - application/xml; charset=utf-8 - - application/json; charset=utf-8 + - application/x-www-form-urlencoded parameters: - name: integer type: integer @@ -883,7 +877,7 @@ paths: description: '' operationId: testJsonFormData consumes: - - application/json + - application/x-www-form-urlencoded parameters: - name: param in: formData @@ -919,6 +913,26 @@ paths: responses: '200': description: successful operation + /fake/body-with-query-params: + put: + tags: + - fake + operationId: testBodyWithQueryParams + parameters: + - name: body + in: body + required: true + schema: + $ref: '#/definitions/User' + - name: query + in: query + required: true + type: string + consumes: + - application/json + responses: + '200': + description: Success /another-fake/dummy: patch: tags: @@ -1446,6 +1460,7 @@ definitions: type: string OuterBoolean: type: boolean + x-codegen-body-parameter-name: boolean_post_body externalDocs: description: Find out more about Swagger url: 'http://swagger.io' diff --git a/modules/openapi-generator/src/test/resources/2_0/petstore_issue_7999.json b/modules/openapi-generator/src/test/resources/2_0/petstore_issue_7999.json new file mode 100644 index 000000000000..7319d725761a --- /dev/null +++ b/modules/openapi-generator/src/test/resources/2_0/petstore_issue_7999.json @@ -0,0 +1,976 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "version": 1.0, + "title": "Swagger Petstore", + "termsOfService": "http://helloreverb.com/terms/", + "contact": { + "email": "apiteam@wordnik.com" + }, + "license": { + "name": "Apache-2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "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/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": false, + "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/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": false, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Validation exception" + }, + "404": { + "description": "Pet not found" + }, + "400": { + "description": "Invalid ID supplied" + } + }, + "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/json", + "application/xml" + ], + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Status values that need to be considered for filter", + "required": false, + "type": "array", + "items": { + "type": "string", + "enum": ["available", "pending", "sold"] + }, + "collectionFormat": "multi", + "default": "available" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + }, + "examples": { + "application/json": { + "name": "Puma", + "type": "Dog", + "color": "Black", + "gender": "Female", + "breed": "Mixed" + } + } + }, + "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/json", + "application/xml" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "Tags to filter by", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi" + } + ], + "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 pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", + "operationId": "getPetById", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "404": { + "description": "Pet not found" + }, + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "400": { + "description": "Invalid ID supplied" + } + }, + "security": [ + { + "api_key": [] + }, + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "post": { + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "string" + }, + { + "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" + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "delete": { + "tags": [ + "pet" + ], + "summary": "Deletes a pet", + "description": "", + "operationId": "deletePet", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "api_key", + "in": "header", + "description": "", + "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", + "application/xml" + ], + "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": { + "default": { + "description": "successful operation" + } + }, + "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", + "application/xml" + ], + "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/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "order placed for purchasing the pet", + "required": false, + "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/json", + "application/xml" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "Order not found" + }, + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid ID supplied" + } + } + }, + "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/json", + "application/xml" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of the order that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "Order not found" + }, + "400": { + "description": "Invalid ID supplied" + } + } + } + }, + "/user": { + "post": { + "tags": [ + "user" + ], + "summary": "Create user", + "description": "This can only be done by the logged in user.", + "operationId": "createUser", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Created user object", + "required": false, + "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/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": false, + "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/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": false, + "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/json", + "application/xml" + ], + "parameters": [ + { + "name": "username", + "in": "query", + "description": "The user name for login", + "required": false, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The password for login in clear text", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "string" + } + }, + "400": { + "description": "Invalid username/password supplied" + } + } + } + }, + "/user/logout": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs out current logged in user session", + "description": "", + "operationId": "logoutUser", + "produces": [ + "application/json", + "application/xml" + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/{username}": { + "get": { + "tags": [ + "user" + ], + "summary": "Get user by user name", + "description": "", + "operationId": "getUserByName", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be fetched. Use user1 for testing. ", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/User" + } + }, + "400": { + "description": "Invalid username supplied" + } + } + }, + "put": { + "tags": [ + "user" + ], + "summary": "Updated user", + "description": "This can only be done by the logged in user.", + "operationId": "updateUser", + "produces": [ + "application/json", + "application/xml" + ], + "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": false, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid user supplied" + } + } + }, + "delete": { + "tags": [ + "user" + ], + "summary": "Delete user", + "description": "This can only be done by the logged in user.", + "operationId": "deleteUser", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid username supplied" + } + } + } + } + }, + "securityDefinitions": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "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" + } + } + }, + "definitions": { + "User": { + "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" + } + }, + "Category": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Category" + } + }, + "Pet": { + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "#/definitions/Category" + }, + "name": { + "type": "string", + "example": "doggie" + }, + "photoUrls": { + "type": "array", + "xml": { + "name": "photoUrl", + "wrapped": true + }, + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "xml": { + "name": "tag", + "wrapped": true + }, + "items": { + "$ref": "#/definitions/Tag" + } + }, + "status": { + "type": "string", + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ] + } + }, + "xml": { + "name": "Pet" + } + }, + "Tag": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Tag" + } + }, + "Order": { + "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" + } + }, + "xml": { + "name": "Order" + } + } + } +} diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml new file mode 100644 index 000000000000..ac2cd975ddf4 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -0,0 +1,1412 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io:80/v2' +info: + description: >- + This spec is mainly for testing Petstore server and contains fake endpoints, + models. Please do not use this for any other purpose. Special characters: " + \ + version: 1.0.0 + title: Swagger Petstore + termsOfService: 'http://swagger.io/terms/' + contact: + email: apiteam@swagger.io + license: + name: Apache-2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: 'http://swagger.io' + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user + externalDocs: + description: Find out more about our store + url: 'http://swagger.io' +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/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 + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/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 + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/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 + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + 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 + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + 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 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{order_id}': + 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 + parameters: + - name: order_id + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/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 + parameters: + - name: order_id + in: path + description: ID of the order that needs to be deleted + required: true + schema: + 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 + responses: + default: + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when toekn expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/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 + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + /fake_classname_test: + patch: + tags: + - 'fake_classname_tags 123#$%^' + summary: To test class name in snake case + description: To test class name in snake case + operationId: testClassname + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + security: + - api_key_query: [] + requestBody: + $ref: '#/components/requestBodies/Client' + /fake: + patch: + tags: + - fake + summary: To test "client" model + description: To test "client" model + operationId: testClientModel + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + requestBody: + $ref: '#/components/requestBodies/Client' + get: + tags: + - fake + summary: To test enum parameters + description: To test enum parameters + operationId: testEnumParameters + parameters: + - name: enum_header_string_array + in: header + explode: true + description: Header parameter enum test (string array) + schema: + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + - name: enum_header_string + in: header + description: Header parameter enum test (string) + schema: + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + - name: enum_query_string_array + in: query + description: Query parameter enum test (string array) + schema: + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + - name: enum_query_string + in: query + description: Query parameter enum test (string) + schema: + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + - name: enum_query_integer + in: query + description: Query parameter enum test (double) + schema: + type: integer + format: int32 + enum: + - 1 + - -2 + - name: enum_query_double + in: query + description: Query parameter enum test (double) + schema: + type: number + format: double + enum: + - 1.1 + - -1.2 + responses: + '400': + description: Invalid request + '404': + description: Not found + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + enum_form_string_array: + description: Form parameter enum test (string array) + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + enum_form_string: + description: Form parameter enum test (string) + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + post: + tags: + - fake + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + operationId: testEndpointParameters + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - http_basic_test: [] + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + integer: + description: None + type: integer + minimum: 10 + maximum: 100 + int32: + description: None + type: integer + format: int32 + minimum: 20 + maximum: 200 + int64: + description: None + type: integer + format: int64 + number: + description: None + type: number + minimum: 32.1 + maximum: 543.2 + float: + description: None + type: number + format: float + maximum: 987.6 + double: + description: None + type: number + format: double + minimum: 67.8 + maximum: 123.4 + string: + description: None + type: string + pattern: '/[a-z]/i' + pattern_without_delimiter: + description: None + type: string + pattern: '^[A-Z].*' + byte: + description: None + type: string + format: byte + binary: + description: None + type: string + format: binary + date: + description: None + type: string + format: date + dateTime: + description: None + type: string + format: date-time + password: + description: None + type: string + format: password + minLength: 10 + maxLength: 64 + callback: + description: None + type: string + required: + - number + - double + - pattern_without_delimiter + - byte + /fake/outer/number: + post: + tags: + - fake + description: Test serialization of outer number types + operationId: fakeOuterNumberSerialize + responses: + '200': + description: Output number + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterNumber' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterNumber' + description: Input number as post body + /fake/outer/string: + post: + tags: + - fake + description: Test serialization of outer string types + operationId: fakeOuterStringSerialize + responses: + '200': + description: Output string + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterString' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterString' + description: Input string as post body + /fake/outer/boolean: + post: + tags: + - fake + description: Test serialization of outer boolean types + operationId: fakeOuterBooleanSerialize + responses: + '200': + description: Output boolean + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterBoolean' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Input boolean as post body + /fake/outer/composite: + post: + tags: + - fake + description: Test serialization of object with outer number type + operationId: fakeOuterCompositeSerialize + responses: + '200': + description: Output composite + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterComposite' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterComposite' + description: Input composite as post body + /fake/jsonFormData: + get: + tags: + - fake + summary: test json serialization of form data + description: '' + operationId: testJsonFormData + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + type: object + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + /fake/inline-additionalProperties: + post: + tags: + - fake + summary: test inline additionalProperties + description: '' + operationId: testInlineAdditionalProperties + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + type: object + additionalProperties: + type: string + description: request body + required: true + /another-fake/dummy: + patch: + tags: + - $another-fake? + summary: To test special tags + description: To test special tags + operationId: test_special_tags + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + requestBody: + $ref: '#/components/requestBodies/Client' +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Client: + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: client model + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + api_key_query: + type: apiKey + name: api_key_query + in: query + http_basic_test: + type: http + scheme: basic + schemas: + Order: + 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: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Category + User: + type: object + properties: + id: + type: integer + format: int64 + x-is-unique: true + 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: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + x-is-unique: true + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + Return: + description: Model for testing reserved words + properties: + return: + type: integer + format: int32 + xml: + name: Return + Name: + description: Model for testing model name same as property name + required: + - name + properties: + name: + type: integer + format: int32 + snake_case: + readOnly: true + type: integer + format: int32 + property: + type: string + 123Number: + type: integer + readOnly: true + xml: + name: Name + 200_response: + description: Model for testing model name starting with number + properties: + name: + type: integer + format: int32 + class: + type: string + xml: + name: Name + ClassModel: + description: Model for testing model with "_class" property + properties: + _class: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Animal' + - type: object + properties: + breed: + type: string + Cat: + allOf: + - $ref: '#/components/schemas/Animal' + - type: object + properties: + declawed: + type: boolean + Animal: + type: object + discriminator: + propertyName: className + required: + - className + properties: + className: + type: string + color: + type: string + default: red + AnimalFarm: + type: array + items: + $ref: '#/components/schemas/Animal' + format_test: + type: object + required: + - number + - byte + - date + - password + properties: + integer: + type: integer + maximum: 100 + minimum: 10 + int32: + type: integer + format: int32 + maximum: 200 + minimum: 20 + int64: + type: integer + format: int64 + number: + maximum: 543.2 + minimum: 32.1 + type: number + float: + type: number + format: float + maximum: 987.6 + minimum: 54.3 + double: + type: number + format: double + maximum: 123.4 + minimum: 67.8 + string: + type: string + pattern: '/[a-z]/i' + byte: + type: string + format: byte + binary: + type: string + format: binary + date: + type: string + format: date + dateTime: + type: string + format: date-time + uuid: + type: string + format: uuid + password: + type: string + format: password + maxLength: 64 + minLength: 10 + EnumClass: + type: string + default: '-efg' + enum: + - _abc + - '-efg' + - (xyz) + Enum_Test: + type: object + required: + - enum_string_required + properties: + enum_string: + type: string + enum: + - UPPER + - lower + - '' + enum_string_required: + type: string + enum: + - UPPER + - lower + - '' + enum_integer: + type: integer + format: int32 + enum: + - 1 + - -1 + enum_number: + type: number + format: double + enum: + - 1.1 + - -1.2 + outerEnum: + $ref: '#/components/schemas/OuterEnum' + AdditionalPropertiesClass: + type: object + properties: + map_property: + type: object + additionalProperties: + type: string + map_of_map_property: + type: object + additionalProperties: + type: object + additionalProperties: + type: string + MixedPropertiesAndAdditionalPropertiesClass: + type: object + properties: + uuid: + type: string + format: uuid + dateTime: + type: string + format: date-time + map: + type: object + additionalProperties: + $ref: '#/components/schemas/Animal' + List: + type: object + properties: + 123-list: + type: string + Client: + type: object + properties: + client: + type: string + ReadOnlyFirst: + type: object + properties: + bar: + type: string + readOnly: true + baz: + type: string + hasOnlyReadOnly: + type: object + properties: + bar: + type: string + readOnly: true + foo: + type: string + readOnly: true + Capitalization: + type: object + properties: + smallCamel: + type: string + CapitalCamel: + type: string + small_Snake: + type: string + Capital_Snake: + type: string + SCA_ETH_Flow_Points: + type: string + ATT_NAME: + description: | + Name of the pet + type: string + MapTest: + type: object + properties: + map_map_of_string: + type: object + additionalProperties: + type: object + additionalProperties: + type: string + map_of_enum_string: + type: object + additionalProperties: + type: string + enum: + - UPPER + - lower + ArrayTest: + type: object + properties: + array_of_string: + type: array + items: + type: string + array_array_of_integer: + type: array + items: + type: array + items: + type: integer + format: int64 + array_array_of_model: + type: array + items: + type: array + items: + $ref: '#/components/schemas/ReadOnlyFirst' + NumberOnly: + type: object + properties: + JustNumber: + type: number + ArrayOfNumberOnly: + type: object + properties: + ArrayNumber: + type: array + items: + type: number + ArrayOfArrayOfNumberOnly: + type: object + properties: + ArrayArrayNumber: + type: array + items: + type: array + items: + type: number + EnumArrays: + type: object + properties: + just_symbol: + type: string + enum: + - '>=' + - $ + array_enum: + type: array + items: + type: string + enum: + - fish + - crab + OuterEnum: + type: string + enum: + - placed + - approved + - delivered + OuterComposite: + type: object + properties: + my_number: + $ref: '#/components/schemas/OuterNumber' + my_string: + $ref: '#/components/schemas/OuterString' + my_boolean: + $ref: '#/components/schemas/OuterBoolean' + OuterNumber: + type: number + OuterString: + type: string + OuterBoolean: + type: boolean + _special_model.name_: + properties: + '$special[property.name]': + type: integer + format: int64 + xml: + name: '$special[model.name]' diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore.yaml new file mode 100644 index 000000000000..a088b689a573 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/petstore.yaml @@ -0,0 +1,710 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. You can find out more about + Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, + #swagger](http://swagger.io/irc/). For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: Swagger Petstore + termsOfService: 'http://swagger.io/terms/' + contact: + email: apiteam@swagger.io + license: + name: Apache-2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: 'http://swagger.io' + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user + externalDocs: + description: Find out more about our store + url: 'http://swagger.io' +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/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 + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/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 + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/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 + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + 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 + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + 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 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/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 + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/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 + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + 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 + responses: + default: + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when toekn expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/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 + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + 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 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + 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/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java new file mode 100644 index 000000000000..ced84fef21a3 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -0,0 +1,1304 @@ +package io.swagger.codegen.languages; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.base.Strings; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.models.Model; +import io.swagger.models.Operation; +import io.swagger.models.Path; +import io.swagger.models.Swagger; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.FormParameter; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; + + +public abstract class AbstractJavaCodegen extends DefaultCodegen implements CodegenConfig { + + static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaCodegen.class); + public static final String FULL_JAVA_UTIL = "fullJavaUtil"; + public static final String DEFAULT_LIBRARY = ""; + public static final String DATE_LIBRARY = "dateLibrary"; + public static final String JAVA8_MODE = "java8"; + public static final String SUPPORT_ASYNC = "supportAsync"; + public static final String WITH_XML = "withXml"; + public static final String SUPPORT_JAVA6 = "supportJava6"; + + protected String dateLibrary = "threetenbp"; + protected boolean supportAsync = false; + protected boolean java8Mode = false; + protected boolean withXml = false; + protected String invokerPackage = "io.swagger"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-java"; + protected String artifactVersion = "1.0.0"; + protected String artifactUrl = "https://github.com/swagger-api/swagger-codegen"; + protected String artifactDescription = "Swagger Java"; + protected String developerName = "Swagger"; + protected String developerEmail = "apiteam@swagger.io"; + protected String developerOrganization = "Swagger"; + protected String developerOrganizationUrl = "http://swagger.io"; + protected String scmConnection = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + protected String scmDeveloperConnection = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + protected String scmUrl = "https://github.com/swagger-api/swagger-codegen"; + protected String licenseName = "Unlicense"; + protected String licenseUrl = "http://unlicense.org"; + protected String projectFolder = "src" + File.separator + "main"; + protected String projectTestFolder = "src" + File.separator + "test"; + protected String sourceFolder = projectFolder + File.separator + "java"; + protected String testFolder = projectTestFolder + File.separator + "java"; + protected String localVariablePrefix = ""; + protected boolean fullJavaUtil; + protected String javaUtilPrefix = ""; + protected Boolean serializableModel = false; + protected boolean serializeBigDecimalAsString = false; + protected boolean hideGenerationTimestamp = false; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + protected boolean supportJava6= false; + + public AbstractJavaCodegen() { + super(); + supportsInheritance = true; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + apiTestTemplateFiles.put("api_test.mustache", ".java"); + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + setReservedWordsLowerCase( + Arrays.asList( + // used as internal variables, can collide with parameter names + "localVarPath", "localVarQueryParams", "localVarCollectionQueryParams", + "localVarHeaderParams", "localVarFormParams", "localVarPostBody", + "localVarAccepts", "localVarAccept", "localVarContentTypes", + "localVarContentType", "localVarAuthNames", "localReturnType", + "ApiClient", "ApiException", "ApiResponse", "Configuration", "StringUtil", + + // language reserved words + "abstract", "continue", "for", "new", "switch", "assert", + "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", "byte", "else", + "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", + "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", + "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", + "native", "super", "while", "null") + ); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object", + "byte[]") + ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); + typeMapping.put("date", "Date"); + typeMapping.put("file", "File"); + + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_URL, CodegenConstants.ARTIFACT_URL_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_DESCRIPTION, CodegenConstants.ARTIFACT_DESCRIPTION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SCM_CONNECTION, CodegenConstants.SCM_CONNECTION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SCM_DEVELOPER_CONNECTION, CodegenConstants.SCM_DEVELOPER_CONNECTION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SCM_URL, CodegenConstants.SCM_URL_DESC)); + cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_NAME, CodegenConstants.DEVELOPER_NAME_DESC)); + cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_EMAIL, CodegenConstants.DEVELOPER_EMAIL_DESC)); + cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_ORGANIZATION, CodegenConstants.DEVELOPER_ORGANIZATION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_ORGANIZATION_URL, CodegenConstants.DEVELOPER_ORGANIZATION_URL_DESC)); + cliOptions.add(new CliOption(CodegenConstants.LICENSE_NAME, CodegenConstants.LICENSE_NAME_DESC)); + cliOptions.add(new CliOption(CodegenConstants.LICENSE_URL, CodegenConstants.LICENSE_URL_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); + cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); + cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); + cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, CodegenConstants + .SERIALIZE_BIG_DECIMAL_AS_STRING_DESC)); + cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util. This option only works for Java API client")); + cliOptions.add(new CliOption("hideGenerationTimestamp", "hides the timestamp when files were generated")); + cliOptions.add(CliOption.newBoolean(WITH_XML, "whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)")); + + CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use"); + Map dateOptions = new HashMap(); + dateOptions.put("java8", "Java 8 native JSR310 (preferred for jdk 1.8+) - note: this also sets \"" + JAVA8_MODE + "\" to true"); + dateOptions.put("threetenbp", "Backport of JSR310 (preferred for jdk < 1.8)"); + dateOptions.put("java8-localdatetime", "Java 8 using LocalDateTime (for legacy app only)"); + dateOptions.put("joda", "Joda (for legacy app only)"); + dateOptions.put("legacy", "Legacy java.util.Date (if you really have a good reason not to use threetenbp"); + dateLibrary.setEnum(dateOptions); + cliOptions.add(dateLibrary); + + CliOption java8Mode = new CliOption(JAVA8_MODE, "Option. Use Java8 classes instead of third party equivalents"); + Map java8ModeOptions = new HashMap(); + java8ModeOptions.put("true", "Use Java 8 classes such as Base64"); + java8ModeOptions.put("false", "Various third party libraries as needed"); + java8Mode.setEnum(java8ModeOptions); + cliOptions.add(java8Mode); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(SUPPORT_JAVA6)) { + this.setSupportJava6(Boolean.valueOf(additionalProperties.get(SUPPORT_JAVA6).toString())); + } + additionalProperties.put(SUPPORT_JAVA6, supportJava6); + + + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + } else if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { + // guess from api package + String derviedInvokerPackage = deriveInvokerPackageName((String)additionalProperties.get(CodegenConstants.API_PACKAGE)); + this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derviedInvokerPackage); + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + LOGGER.info("Invoker Package Name, originally not set, is now dervied from api package name: " + derviedInvokerPackage); + } else if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { + // guess from model package + String derviedInvokerPackage = deriveInvokerPackageName((String)additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); + this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derviedInvokerPackage); + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + LOGGER.info("Invoker Package Name, originally not set, is now dervied from model package name: " + derviedInvokerPackage); + } else { + //not set, use default to be passed to template + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + } + + if (additionalProperties.containsKey(CodegenConstants.GROUP_ID)) { + this.setGroupId((String) additionalProperties.get(CodegenConstants.GROUP_ID)); + } else { + //not set, use to be passed to template + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + } + + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_ID)) { + this.setArtifactId((String) additionalProperties.get(CodegenConstants.ARTIFACT_ID)); + } else { + //not set, use to be passed to template + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + } + + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { + this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION)); + } else { + //not set, use to be passed to template + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + } + + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_URL)) { + this.setArtifactUrl((String) additionalProperties.get(CodegenConstants.ARTIFACT_URL)); + } else { + additionalProperties.put(CodegenConstants.ARTIFACT_URL, artifactUrl); + } + + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_DESCRIPTION)) { + this.setArtifactDescription((String) additionalProperties.get(CodegenConstants.ARTIFACT_DESCRIPTION)); + } else { + additionalProperties.put(CodegenConstants.ARTIFACT_DESCRIPTION, artifactDescription); + } + + if (additionalProperties.containsKey(CodegenConstants.SCM_CONNECTION)) { + this.setScmConnection((String) additionalProperties.get(CodegenConstants.SCM_CONNECTION)); + } else { + additionalProperties.put(CodegenConstants.SCM_CONNECTION, scmConnection); + } + + if (additionalProperties.containsKey(CodegenConstants.SCM_DEVELOPER_CONNECTION)) { + this.setScmDeveloperConnection((String) additionalProperties.get(CodegenConstants.SCM_DEVELOPER_CONNECTION)); + } else { + additionalProperties.put(CodegenConstants.SCM_DEVELOPER_CONNECTION, scmDeveloperConnection); + } + + if (additionalProperties.containsKey(CodegenConstants.SCM_URL)) { + this.setScmUrl((String) additionalProperties.get(CodegenConstants.SCM_URL)); + } else { + additionalProperties.put(CodegenConstants.SCM_URL, scmUrl); + } + + if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_NAME)) { + this.setDeveloperName((String) additionalProperties.get(CodegenConstants.DEVELOPER_NAME)); + } else { + additionalProperties.put(CodegenConstants.DEVELOPER_NAME, developerName); + } + + if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_EMAIL)) { + this.setDeveloperEmail((String) additionalProperties.get(CodegenConstants.DEVELOPER_EMAIL)); + } else { + additionalProperties.put(CodegenConstants.DEVELOPER_EMAIL, developerEmail); + } + + if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_ORGANIZATION)) { + this.setDeveloperOrganization((String) additionalProperties.get(CodegenConstants.DEVELOPER_ORGANIZATION)); + } else { + additionalProperties.put(CodegenConstants.DEVELOPER_ORGANIZATION, developerOrganization); + } + + if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_ORGANIZATION_URL)) { + this.setDeveloperOrganizationUrl((String) additionalProperties.get(CodegenConstants.DEVELOPER_ORGANIZATION_URL)); + } else { + additionalProperties.put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, developerOrganizationUrl); + } + + if (additionalProperties.containsKey(CodegenConstants.LICENSE_NAME)) { + this.setLicenseName((String) additionalProperties.get(CodegenConstants.LICENSE_NAME)); + } else { + additionalProperties.put(CodegenConstants.LICENSE_NAME, licenseName); + } + + if (additionalProperties.containsKey(CodegenConstants.LICENSE_URL)) { + this.setLicenseUrl((String) additionalProperties.get(CodegenConstants.LICENSE_URL)); + } else { + additionalProperties.put(CodegenConstants.LICENSE_URL, licenseUrl); + } + + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); + } + + if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) { + this.setLocalVariablePrefix((String) additionalProperties.get(CodegenConstants.LOCAL_VARIABLE_PREFIX)); + } + + if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) { + this.setSerializableModel(Boolean.valueOf(additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); + } + + if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) { + this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); + } + + if(additionalProperties.containsKey(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING)) { + this.setSerializeBigDecimalAsString(Boolean.valueOf(additionalProperties.get(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING).toString())); + } + + // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string + additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); + + if (additionalProperties.containsKey(FULL_JAVA_UTIL)) { + this.setFullJavaUtil(Boolean.valueOf(additionalProperties.get(FULL_JAVA_UTIL).toString())); + } + + if (fullJavaUtil) { + javaUtilPrefix = "java.util."; + } + additionalProperties.put(FULL_JAVA_UTIL, fullJavaUtil); + additionalProperties.put("javaUtilPrefix", javaUtilPrefix); + + if (additionalProperties.containsKey(WITH_XML)) { + this.setWithXml(Boolean.valueOf(additionalProperties.get(WITH_XML).toString())); + } + additionalProperties.put(WITH_XML, withXml); + + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + + importMapping.put("List", "java.util.List"); + + if (fullJavaUtil) { + typeMapping.put("array", "java.util.List"); + typeMapping.put("map", "java.util.Map"); + typeMapping.put("DateTime", "java.util.Date"); + typeMapping.put("UUID", "java.util.UUID"); + typeMapping.remove("List"); + importMapping.remove("Date"); + importMapping.remove("Map"); + importMapping.remove("HashMap"); + importMapping.remove("Array"); + importMapping.remove("ArrayList"); + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("DateTime"); + importMapping.remove("UUID"); + instantiationTypes.put("array", "java.util.ArrayList"); + instantiationTypes.put("map", "java.util.HashMap"); + } + + this.sanitizeConfig(); + + // 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"); + + // imports for pojos + importMapping.put("ApiModelProperty", "io.swagger.annotations.ApiModelProperty"); + importMapping.put("ApiModel", "io.swagger.annotations.ApiModel"); + importMapping.put("JsonProperty", "com.fasterxml.jackson.annotation.JsonProperty"); + importMapping.put("JsonSubTypes", "com.fasterxml.jackson.annotation.JsonSubTypes"); + importMapping.put("JsonTypeInfo", "com.fasterxml.jackson.annotation.JsonTypeInfo"); + importMapping.put("JsonCreator", "com.fasterxml.jackson.annotation.JsonCreator"); + importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue"); + importMapping.put("SerializedName", "com.google.gson.annotations.SerializedName"); + importMapping.put("TypeAdapter", "com.google.gson.TypeAdapter"); + importMapping.put("JsonAdapter", "com.google.gson.annotations.JsonAdapter"); + importMapping.put("JsonReader", "com.google.gson.stream.JsonReader"); + importMapping.put("JsonWriter", "com.google.gson.stream.JsonWriter"); + importMapping.put("IOException", "java.io.IOException"); + importMapping.put("Objects", "java.util.Objects"); + importMapping.put("StringUtil", invokerPackage + ".StringUtil"); + // 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"); + + if (additionalProperties.containsKey(JAVA8_MODE)) { + setJava8Mode(Boolean.parseBoolean(additionalProperties.get(JAVA8_MODE).toString())); + if ( java8Mode ) { + additionalProperties.put("java8", "true"); + } + } + + if (additionalProperties.containsKey(SUPPORT_ASYNC)) { + setSupportAsync(Boolean.parseBoolean(additionalProperties.get(SUPPORT_ASYNC).toString())); + if (supportAsync) { + additionalProperties.put(SUPPORT_ASYNC, "true"); + } + } + + if (additionalProperties.containsKey(WITH_XML)) { + setWithXml(Boolean.parseBoolean(additionalProperties.get(WITH_XML).toString())); + if ( withXml ) { + additionalProperties.put(WITH_XML, "true"); + } + } + + if (additionalProperties.containsKey(DATE_LIBRARY)) { + setDateLibrary(additionalProperties.get("dateLibrary").toString()); + } + + if ("threetenbp".equals(dateLibrary)) { + additionalProperties.put("threetenbp", "true"); + additionalProperties.put("jsr310", "true"); + typeMapping.put("date", "LocalDate"); + typeMapping.put("DateTime", "OffsetDateTime"); + importMapping.put("LocalDate", "org.threeten.bp.LocalDate"); + importMapping.put("OffsetDateTime", "org.threeten.bp.OffsetDateTime"); + } else if ("joda".equals(dateLibrary)) { + additionalProperties.put("joda", "true"); + typeMapping.put("date", "LocalDate"); + typeMapping.put("DateTime", "DateTime"); + importMapping.put("LocalDate", "org.joda.time.LocalDate"); + importMapping.put("DateTime", "org.joda.time.DateTime"); + } else if (dateLibrary.startsWith("java8")) { + additionalProperties.put("java8", "true"); + additionalProperties.put("jsr310", "true"); + typeMapping.put("date", "LocalDate"); + importMapping.put("LocalDate", "java.time.LocalDate"); + if ("java8-localdatetime".equals(dateLibrary)) { + typeMapping.put("DateTime", "LocalDateTime"); + importMapping.put("LocalDateTime", "java.time.LocalDateTime"); + } else { + typeMapping.put("DateTime", "OffsetDateTime"); + importMapping.put("OffsetDateTime", "java.time.OffsetDateTime"); + } + } else if (dateLibrary.equals("legacy")) { + additionalProperties.put("legacyDates", "true"); + } + } + + private void sanitizeConfig() { + // Sanitize any config options here. We also have to update the additionalProperties because + // the whole additionalProperties object is injected into the main object passed to the mustache layer + + this.setApiPackage(sanitizePackageName(apiPackage)); + if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { + this.additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); + } + + this.setModelPackage(sanitizePackageName(modelPackage)); + if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { + this.additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); + } + + this.setInvokerPackage(sanitizePackageName(invokerPackage)); + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + } + } + + @Override + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/'); + } + + @Override + public String apiTestFileFolder() { + return outputFolder + "/" + testFolder + "/" + apiPackage().replace('.', '/'); + } + + @Override + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/'); + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiTestFilename(String name) { + return toApiName(name) + "Test"; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + return camelize(name) + "Api"; + } + + @Override + public String toApiFilename(String name) { + return toApiName(name); + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + if (name.toLowerCase().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() + name.substring(2); + } + + // camelize (lower first character) the variable name + // pet_id => petId + name = camelize(name, true); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + private boolean startsWithTwoUppercaseLetters(String name) { + boolean startsWithTwoUppercaseLetters = false; + if(name.length() > 1) { + startsWithTwoUppercaseLetters = name.substring(0, 2).equals(name.substring(0, 2).toUpperCase()); + } + return startsWithTwoUppercaseLetters; + } + + @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 toModelName(final String name) { + // We need to check if import-mapping has a different model for this class, so we use it + // instead of the auto-generated one. + if (importMapping.containsKey(name)) { + return importMapping.get(name); + } + + final String sanitizedName = sanitizeName(name); + + String nameWithPrefixSuffix = sanitizedName; + if (!StringUtils.isEmpty(modelNamePrefix)) { + // add '_' so that model name can be camelized correctly + nameWithPrefixSuffix = modelNamePrefix + "_" + nameWithPrefixSuffix; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + // add '_' so that model name can be camelized correctly + nameWithPrefixSuffix = nameWithPrefixSuffix + "_" + modelNameSuffix; + } + + // camelize the model name + // phone_number => PhoneNumber + final String camelizedName = camelize(nameWithPrefixSuffix); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(camelizedName)) { + final String modelName = "Model" + camelizedName; + LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + + // model name starts with number + if (camelizedName.matches("^\\d.*")) { + final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + + return camelizedName; + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + if (inner == null) { + LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined"); + // TODO maybe better defaulting to StringProperty than returning null + return null; + } + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + if (inner == null) { + LOGGER.warn(mp.getName() + "(map property) does not have a proper inner type defined"); + // TODO maybe better defaulting to StringProperty than returning null + return null; + } + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getAlias(String name) { + if (typeAliases != null && typeAliases.containsKey(name)) { + return typeAliases.get(name); + } + return name; + } + + @Override + public String toDefaultValue(Property p) { + if (p instanceof ArrayProperty) { + final ArrayProperty ap = (ArrayProperty) p; + final String pattern; + if (fullJavaUtil) { + pattern = "new java.util.ArrayList<%s>()"; + } else { + pattern = "new ArrayList<%s>()"; + } + if (ap.getItems() == null) { + return null; + } + + String typeDeclaration = getTypeDeclaration(ap.getItems()); + Object java8obj = additionalProperties.get("java8"); + if (java8obj != null) { + Boolean java8 = Boolean.valueOf(java8obj.toString()); + if (java8 != null && java8) { + typeDeclaration = ""; + } + } + + return String.format(pattern, typeDeclaration); + } else if (p instanceof MapProperty) { + final MapProperty ap = (MapProperty) p; + final String pattern; + if (fullJavaUtil) { + pattern = "new java.util.HashMap<%s>()"; + } else { + pattern = "new HashMap<%s>()"; + } + if (ap.getAdditionalProperties() == null) { + return null; + } + + String typeDeclaration = String.format("String, %s", getTypeDeclaration(ap.getAdditionalProperties())); + Object java8obj = additionalProperties.get("java8"); + if (java8obj != null) { + Boolean java8 = Boolean.valueOf(java8obj.toString()); + if (java8 != null && java8) { + typeDeclaration = ""; + } + } + + return String.format(pattern, typeDeclaration); + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "null"; + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString()+"l"; + } + return "null"; + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString() + "d"; + } + return "null"; + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString() + "f"; + } + return "null"; + } else if (p instanceof BooleanProperty) { + BooleanProperty bp = (BooleanProperty) p; + if (bp.getDefault() != null) { + return bp.getDefault().toString(); + } + return "null"; + } else if (p instanceof StringProperty) { + StringProperty sp = (StringProperty) p; + if (sp.getDefault() != null) { + String _default = sp.getDefault(); + if (sp.getEnum() == null) { + return "\"" + escapeText(_default) + "\""; + } else { + // convert to enum var name later in postProcessModels + return _default; + } + } + return "null"; + } + return super.toDefaultValue(p); + } + + @Override + public void setParameterExampleValue(CodegenParameter p) { + String example; + + if (p.defaultValue == null) { + example = p.example; + } else { + example = p.defaultValue; + } + + String type = p.baseType; + if (type == null) { + type = p.dataType; + } + + if ("String".equals(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "\"" + escapeText(example) + "\""; + } else if ("Integer".equals(type) || "Short".equals(type)) { + if (example == null) { + example = "56"; + } + } else if ("Long".equals(type)) { + if (example == null) { + example = "56"; + } + example = example + "L"; + } else if ("Float".equals(type)) { + if (example == null) { + example = "3.4"; + } + example = example + "F"; + } else if ("Double".equals(type)) { + example = "3.4"; + example = example + "D"; + } else if ("Boolean".equals(type)) { + if (example == null) { + example = "true"; + } + } else if ("File".equals(type)) { + if (example == null) { + example = "/path/to/file"; + } + example = "new File(\"" + escapeText(example) + "\")"; + } else if ("Date".equals(type)) { + example = "new Date()"; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + example = "new " + type + "()"; + } + + if (example == null) { + example = "null"; + } else if (Boolean.TRUE.equals(p.isListContainer)) { + example = "Arrays.asList(" + example + ")"; + } else if (Boolean.TRUE.equals(p.isMapContainer)) { + example = "new HashMap()"; + } + + p.example = example; + } + + @Override + public String toExampleValue(Property p) { + if(p.getExample() != null) { + return escapeText(p.getExample().toString()); + } else { + return super.toExampleValue(p); + } + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + + swaggerType = getAlias(swaggerType); + + // don't apply renaming on types from the typeMapping + if (typeMapping.containsKey(swaggerType)) { + return typeMapping.get(swaggerType); + } + + if (null == swaggerType) { + LOGGER.error("No Type defined for Property " + p); + } + return toModelName(swaggerType); + } + + @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; + } + + return operationId; + } + + @Override + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); + if(codegenModel.description != null) { + codegenModel.imports.add("ApiModel"); + } + if (codegenModel.discriminator != null && additionalProperties.containsKey("jackson")) { + codegenModel.imports.add("JsonSubTypes"); + codegenModel.imports.add("JsonTypeInfo"); + } + if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { + final Model parentModel = allDefinitions.get(codegenModel.parentSchema); + final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); + codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); + } + return codegenModel; + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + if(serializeBigDecimalAsString) { + if (property.baseType.equals("BigDecimal")) { + // we serialize BigDecimal as `string` to avoid precision loss + property.vendorExtensions.put("extraAnnotation", "@JsonSerialize(using = ToStringSerializer.class)"); + + // this requires some more imports to be added for this model... + model.imports.add("ToStringSerializer"); + model.imports.add("JsonSerialize"); + } + } + + if (!fullJavaUtil) { + if ("array".equals(property.containerType)) { + model.imports.add("ArrayList"); + } else if ("map".equals(property.containerType)) { + model.imports.add("HashMap"); + } + } + + if(!BooleanUtils.toBoolean(model.isEnum)) { + // needed by all pojos, but not enums + model.imports.add("ApiModelProperty"); + model.imports.add("ApiModel"); + } + } + + @Override + public void postProcessParameter(CodegenParameter parameter) { } + + @Override + public Map postProcessModels(Map objs) { + // recursively add import for mapping one type to multiple imports + List> recursiveImports = (List>) objs.get("imports"); + if (recursiveImports == null) + return objs; + + ListIterator> listIterator = recursiveImports.listIterator(); + while (listIterator.hasNext()) { + String _import = listIterator.next().get("import"); + // if the import package happens to be found in the importMapping (key) + // add the corresponding import package to the list + if (importMapping.containsKey(_import)) { + Map newImportMap= new HashMap(); + newImportMap.put("import", importMapping.get(_import)); + listIterator.add(newImportMap); + } + } + + return postProcessModelsEnum(objs); + } + + @Override + public Map postProcessOperations(Map objs) { + // Remove imports of List, ArrayList, Map and HashMap as they are + // imported in the template already. + List> imports = (List>) objs.get("imports"); + Pattern pattern = Pattern.compile("java\\.util\\.(List|ArrayList|Map|HashMap)"); + for (Iterator> itr = imports.iterator(); itr.hasNext();) { + String _import = itr.next().get("import"); + if (pattern.matcher(_import).matches()) { + itr.remove(); + } + } + return objs; + } + + @Override + public void preprocessSwagger(Swagger swagger) { + if (swagger == null || swagger.getPaths() == null){ + return; + } + for (String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if (path.getOperations() == null){ + continue; + } + for (Operation operation : path.getOperations()) { + boolean hasFormParameters = false; + boolean hasBodyParameters = false; + for (Parameter parameter : operation.getParameters()) { + if (parameter instanceof FormParameter) { + hasFormParameters = true; + } + if (parameter instanceof BodyParameter) { + hasBodyParameters = true; + } + } + if (hasBodyParameters || hasFormParameters){ + String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json"; + String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty() ? defaultContentType : operation.getConsumes().get(0); + operation.setVendorExtension("x-contentType", contentType); + } + String accepts = getAccept(operation); + operation.setVendorExtension("x-accepts", accepts); + } + } + } + + private static String getAccept(Operation operation) { + String accepts = null; + String defaultContentType = "application/json"; + if (operation.getProduces() != null && !operation.getProduces().isEmpty()) { + StringBuilder sb = new StringBuilder(); + for (String produces : operation.getProduces()) { + if (defaultContentType.equalsIgnoreCase(produces)) { + accepts = defaultContentType; + break; + } else { + if (sb.length() > 0) { + sb.append(","); + } + sb.append(produces); + } + } + if (accepts == null) { + accepts = sb.toString(); + } + } else { + accepts = defaultContentType; + } + + return accepts; + } + + @Override + protected boolean needToImport(String type) { + return super.needToImport(type) && type.indexOf(".") < 0; + } +/* + @Override + public String findCommonPrefixOfVars(List vars) { + String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()])); + // exclude trailing characters that should be part of a valid variable + // e.g. ["status-on", "status-off"] => "status-" (not "status-o") + return prefix.replaceAll("[a-zA-Z0-9]+\\z", ""); + } +*/ + + @Override + public String toEnumName(CodegenProperty property) { + return sanitizeName(camelize(property.name)) + "Enum"; + } + + @Override + public String toEnumVarName(String value, String datatype) { + if (value.length() == 0) { + return "EMPTY"; + } + + // for symbol, e.g. $, # + if (getSymbolName(value) != null) { + return getSymbolName(value).toUpperCase(); + } + + // number + if ("Integer".equals(datatype) || "Long".equals(datatype) || + "Float".equals(datatype) || "Double".equals(datatype)) { + String varName = "NUMBER_" + value; + varName = varName.replaceAll("-", "MINUS_"); + varName = varName.replaceAll("\\+", "PLUS_"); + varName = varName.replaceAll("\\.", "_DOT_"); + return varName; + } + + // string + String var = value.replaceAll("\\W+", "_").toUpperCase(); + if (var.matches("\\d.*")) { + return "_" + var; + } else { + return var; + } + } + + @Override + public String toEnumValue(String value, String datatype) { + if ("Integer".equals(datatype) || "Double".equals(datatype)) { + return value; + } else if ("Long".equals(datatype)) { + // add l to number, e.g. 2048 => 2048l + return value + "l"; + } else if ("Float".equals(datatype)) { + // add f to number, e.g. 3.14 => 3.14f + return value + "f"; + } else { + return "\"" + escapeText(value) + "\""; + } + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + op.path = sanitizePath(op.path); + return op; + } + + private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + // This generator uses inline classes to define enums, which breaks when + // dealing with models that have subTypes. To clean this up, we will analyze + // the parent and child models, look for enums that match, and remove + // them from the child models and leave them in the parent. + // Because the child models extend the parents, the enums will be available via the parent. + + // Only bother with reconciliation if the parent model has enums. + if (!parentCodegenModel.hasEnums) { + return codegenModel; + } + + // Get the properties for the parent and child models + final List parentModelCodegenProperties = parentCodegenModel.vars; + List codegenProperties = codegenModel.vars; + + // Iterate over all of the parent model properties + boolean removedChildEnum = false; + for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) { + // Look for enums + if (parentModelCodegenPropery.isEnum) { + // Now that we have found an enum in the parent class, + // and search the child class for the same enum. + Iterator iterator = codegenProperties.iterator(); + while (iterator.hasNext()) { + CodegenProperty codegenProperty = iterator.next(); + if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) { + // We found an enum in the child class that is + // a duplicate of the one in the parent, so remove it. + iterator.remove(); + removedChildEnum = true; + } + } + } + } + + if(removedChildEnum) { + // If we removed an entry from this model's vars, we need to ensure hasMore is updated + int count = 0, numVars = codegenProperties.size(); + for(CodegenProperty codegenProperty : codegenProperties) { + count += 1; + codegenProperty.hasMore = (count < numVars) ? true : false; + } + codegenModel.vars = codegenProperties; + } + return codegenModel; + } + + private static String sanitizePackageName(String packageName) { + packageName = packageName.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_"); + if(Strings.isNullOrEmpty(packageName)) { + return "invalidPackageName"; + } + return packageName; + } + + public void setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public void setArtifactId(String artifactId) { + this.artifactId = artifactId; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public void setArtifactUrl(String artifactUrl) { + this.artifactUrl = artifactUrl; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public void setScmConnection(String scmConnection) { + this.scmConnection = scmConnection; + } + + public void setScmDeveloperConnection(String scmDeveloperConnection) { + this.scmDeveloperConnection = scmDeveloperConnection; + } + + public void setScmUrl(String scmUrl) { + this.scmUrl = scmUrl; + } + + public void setDeveloperName(String developerName) { + this.developerName = developerName; + } + + public void setDeveloperEmail(String developerEmail) { + this.developerEmail = developerEmail; + } + + public void setDeveloperOrganization(String developerOrganization) { + this.developerOrganization = developerOrganization; + } + + public void setDeveloperOrganizationUrl(String developerOrganizationUrl) { + this.developerOrganizationUrl = developerOrganizationUrl; + } + + public void setLicenseName(String licenseName) { + this.licenseName = licenseName; + } + + public void setLicenseUrl(String licenseUrl) { + this.licenseUrl = licenseUrl; + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + + public void setTestFolder(String testFolder) { + this.testFolder = testFolder; + } + + public void setLocalVariablePrefix(String localVariablePrefix) { + this.localVariablePrefix = localVariablePrefix; + } + + public void setSerializeBigDecimalAsString(boolean s) { + this.serializeBigDecimalAsString = s; + } + + public void setSerializableModel(Boolean serializableModel) { + this.serializableModel = serializableModel; + } + + private String sanitizePath(String p) { + //prefer replace a ", instead of a fuLL URL encode for readability + return p.replaceAll("\"", "%22"); + } + + public void setFullJavaUtil(boolean fullJavaUtil) { + this.fullJavaUtil = fullJavaUtil; + } + + public void setWithXml(boolean withXml) { + this.withXml = withXml; + } + + public void setDateLibrary(String library) { + this.dateLibrary = library; + } + + public void setJava8Mode(boolean enabled) { + this.java8Mode = enabled; + } + + public void setSupportAsync(boolean enabled) { + this.supportAsync = enabled; + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + /* + * Derive invoker package name based on the input + * e.g. foo.bar.model => foo.bar + * + * @param input API package/model name + * @return Derived invoker package name based on API package/model name + */ + private String deriveInvokerPackageName(String input) { + String[] parts = input.split(Pattern.quote(".")); // Split on period. + + StringBuilder sb = new StringBuilder(); + String delim = ""; + for (String p : Arrays.copyOf(parts, parts.length-1)) { + sb.append(delim).append(p); + delim = "."; + } + return sb.toString(); + } + + public void setSupportJava6(boolean value) { + this.supportJava6 = value; + } + + public String toRegularExpression(String pattern) { + return escapeText(pattern); + } + + public boolean convertPropertyToBoolean(String propertyKey) { + boolean booleanValue = false; + if (additionalProperties.containsKey(propertyKey)) { + booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString()); + } + + return booleanValue; + } + + public void writePropertyBack(String propertyKey, boolean value) { + additionalProperties.put(propertyKey, value); + } + + /** + * Output the partial Getter name for boolean property, e.g. Active + * + * @param name the name of the property + * @return partial getter name based on naming convention + */ + public String toBooleanGetter(String name) { + return getterAndSetterCapitalize(name); + } + + @Override + public String sanitizeTag(String tag) { + tag = camelize(underscore(sanitizeName(tag))); + + // tag starts with numbers + if (tag.matches("^\\d.*")) { + tag = "Class" + tag; + } + return tag; + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptInversifyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptInversifyClientCodegen.java new file mode 100644 index 000000000000..56c224c0649d --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptInversifyClientCodegen.java @@ -0,0 +1,373 @@ +package io.swagger.codegen.languages; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.utils.SemVer; +import io.swagger.models.ModelImpl; +import io.swagger.models.properties.*; + +public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCodegen { + private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm"); + private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value"; + + public static final String NPM_NAME = "npmName"; + public static final String NPM_VERSION = "npmVersion"; + public static final String NPM_REPOSITORY = "npmRepository"; + public static final String SNAPSHOT = "snapshot"; + public static final String WITH_INTERFACES = "withInterfaces"; + public static final String USE_PROMISE = "usePromise"; + public static final String TAGGED_UNIONS ="taggedUnions"; + + protected String npmVersion = null; + protected String npmName = null; + protected String npmRepository = null; + private boolean taggedUnions = false; + + public TypeScriptInversifyClientCodegen() { + super(); + this.outputFolder = "generated-code/typescript-inversify"; + + embeddedTemplateDir = templateDir = "typescript-inversify"; + modelTemplateFiles.put("model.mustache", ".ts"); + apiTemplateFiles.put("api.service.mustache", ".ts"); + languageSpecificPrimitives.add("Blob"); + typeMapping.put("file", "Blob"); + apiPackage = "api"; + modelPackage = "model"; + + this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package")); + this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package")); + this.cliOptions.add(new CliOption(NPM_REPOSITORY, + "Use this property to set an url your private npmRepo in the package.json")); + this.cliOptions.add(new CliOption(SNAPSHOT, + "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", + BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(WITH_INTERFACES, + "Setting this property to true will generate interfaces next to the default class implementations.", + BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(USE_PROMISE, + "Setting this property to use promise instead of observable inside every service.", + BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(TAGGED_UNIONS, + "Use discriminators to create tagged unions instead of extending interfaces.", + BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); + } + + @Override + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { + codegenModel.additionalPropertiesType = getTypeDeclaration(swaggerModel.getAdditionalProperties()); + addImport(codegenModel, codegenModel.additionalPropertiesType); + } + + @Override + public String getName() { + return "typescript-inversify"; + } + + @Override + public String getHelp() { + return "Generates Typescript services using Inversify IOC"; + } + + @Override + public void processOpts() { + super.processOpts(); + // HttpClient + supportingFiles.add(new SupportingFile("IHttpClient.mustache", getIndexDirectory(), "IHttpClient.ts")); + supportingFiles.add(new SupportingFile("IAPIConfiguration.mustache", getIndexDirectory(), "IAPIConfiguration.ts")); + supportingFiles.add(new SupportingFile("HttpClient.mustache", getIndexDirectory(), "HttpClient.ts")); + supportingFiles.add(new SupportingFile("HttpResponse.mustache", getIndexDirectory(), "HttpResponse.ts")); + supportingFiles.add(new SupportingFile("Headers.mustache", getIndexDirectory(), "Headers.ts")); + + supportingFiles.add(new SupportingFile("ApiServiceBinder.mustache", getIndexDirectory(), "ApiServiceBinder.ts")); + supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts")); + + if (additionalProperties.containsKey(NPM_NAME)) { + addNpmPackageGeneration(); + } + + if (additionalProperties.containsKey(WITH_INTERFACES)) { + boolean withInterfaces = Boolean.parseBoolean(additionalProperties.get(WITH_INTERFACES).toString()); + if (withInterfaces) { + apiTemplateFiles.put("apiInterface.mustache", "Interface.ts"); + } + } + + if (additionalProperties.containsKey(TAGGED_UNIONS)) { + taggedUnions = Boolean.parseBoolean(additionalProperties.get(TAGGED_UNIONS).toString()); + } + } + + private void addNpmPackageGeneration() { + if (additionalProperties.containsKey(NPM_NAME)) { + this.setNpmName(additionalProperties.get(NPM_NAME).toString()); + } + + if (additionalProperties.containsKey(NPM_VERSION)) { + this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString()); + } + + if (additionalProperties.containsKey(SNAPSHOT) + && Boolean.valueOf(additionalProperties.get(SNAPSHOT).toString())) { + this.setNpmVersion(npmVersion + "-SNAPSHOT." + SNAPSHOT_SUFFIX_FORMAT.format(new Date())); + } + additionalProperties.put(NPM_VERSION, npmVersion); + + if (additionalProperties.containsKey(NPM_REPOSITORY)) { + this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString()); + } + + //Files for building our lib + supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts")); + supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts")); + supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts")); + supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("README.mustache", getIndexDirectory(), "README.md")); + supportingFiles.add(new SupportingFile("package.mustache", getIndexDirectory(), "package.json")); + supportingFiles.add(new SupportingFile("tsconfig.mustache", getIndexDirectory(), "tsconfig.json")); + } + + private String getIndexDirectory() { + String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.'))); + return indexPackage.replace('.', File.separatorChar); + } + + @Override + public boolean isDataTypeFile(final String dataType) { + return dataType != null && dataType.equals("Blob"); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof FileProperty) { + return "Blob"; + } else if (p instanceof ObjectProperty) { + return "any"; + } else { + return super.getTypeDeclaration(p); + } + } + + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + if (isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { + return swaggerType; + } + applyLocalTypeMapping(swaggerType); + return swaggerType; + } + + private String applyLocalTypeMapping(String type) { + if (typeMapping.containsKey(type)) { + type = typeMapping.get(type); + } + return type; + } + + private boolean isLanguagePrimitive(String type) { + return languageSpecificPrimitives.contains(type); + } + + private boolean isLanguageGenericType(String type) { + for (String genericType : languageGenericTypes) { + if (type.startsWith(genericType + "<")) { + return true; + } + } + return false; + } + + @Override + public void postProcessParameter(CodegenParameter parameter) { + super.postProcessParameter(parameter); + parameter.dataType = applyLocalTypeMapping(parameter.dataType); + } + + @Override + public Map postProcessOperations(Map operations) { + Map objs = (Map) operations.get("operations"); + + // Add filename information for api imports + objs.put("apiFilename", getApiFilenameFromClassname(objs.get("classname").toString())); + + List ops = (List) objs.get("operation"); + for (CodegenOperation op : ops) { + // Prep a string buffer where we're going to set up our new version of the string. + StringBuilder pathBuffer = new StringBuilder(); + StringBuilder parameterName = new StringBuilder(); + int insideCurly = 0; + + op.httpMethod = op.httpMethod.toLowerCase(); + + // Iterate through existing string, one character at a time. + for (int i = 0; i < op.path.length(); i++) { + switch (op.path.charAt(i)) { + case '{': + // We entered curly braces, so track that. + insideCurly++; + + // Add the more complicated component instead of just the brace. + pathBuffer.append("${encodeURIComponent(String("); + break; + case '}': + // We exited curly braces, so track that. + insideCurly--; + + // Add the more complicated component instead of just the brace. + pathBuffer.append(toVarName(parameterName.toString())); + pathBuffer.append("))}"); + parameterName.setLength(0); + break; + default: + if (insideCurly > 0) { + parameterName.append(op.path.charAt(i)); + } else { + pathBuffer.append(op.path.charAt(i)); + } + break; + } + } + + // Overwrite path to TypeScript template string, after applying everything we just did. + op.path = pathBuffer.toString(); + } + + // Add additional filename information for model imports in the services + List> imports = (List>) operations.get("imports"); + for (Map im : imports) { + im.put("filename", im.get("import")); + im.put("classname", getModelnameFromModelFilename(im.get("filename").toString())); + } + + return operations; + } + + @Override + public Map postProcessModels(Map objs) { + Map result = super.postProcessModels(objs); + + return postProcessModelsEnum(result); + } + + @Override + public Map postProcessAllModels(Map objs) { + Map result = super.postProcessAllModels(objs); + + for (Map.Entry entry : result.entrySet()) { + Map inner = (Map) entry.getValue(); + List> models = (List>) inner.get("models"); + for (Map mo : models) { + CodegenModel cm = (CodegenModel) mo.get("model"); + if (taggedUnions) { + mo.put(TAGGED_UNIONS, true); + if (cm.discriminator != null && cm.children != null) { + for (CodegenModel child : cm.children) { + cm.imports.add(child.classname); + } + } + if (cm.parent != null) { + cm.imports.remove(cm.parent); + } + } + // Add additional filename information for imports + mo.put("tsImports", toTsImports(cm, cm.imports)); + } + } + return result; + } + + private List> toTsImports(CodegenModel cm, Set imports) { + List> tsImports = new ArrayList<>(); + for (String im : imports) { + if (!im.equals(cm.classname)) { + HashMap tsImport = new HashMap<>(); + tsImport.put("classname", im); + tsImport.put("filename", toModelFilename(im)); + tsImports.add(tsImport); + } + } + return tsImports; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultService"; + } + return initialCaps(name) + "Service"; + } + + @Override + public String toApiFilename(String name) { + if (name.length() == 0) { + return "default.service"; + } + return camelize(name, true) + ".service"; + } + + @Override + public String toApiImport(String name) { + return apiPackage() + "/" + toApiFilename(name); + } + + @Override + public String toModelFilename(String name) { + return camelize(toModelName(name), true); + } + + @Override + public String toModelImport(String name) { + return modelPackage() + "/" + toModelFilename(name); + } + + public String getNpmName() { + return npmName; + } + + public void setNpmName(String npmName) { + this.npmName = npmName; + } + + public String getNpmVersion() { + return npmVersion; + } + + public void setNpmVersion(String npmVersion) { + this.npmVersion = npmVersion; + } + + public String getNpmRepository() { + return npmRepository; + } + + public void setNpmRepository(String npmRepository) { + this.npmRepository = npmRepository; + } + + private String getApiFilenameFromClassname(String classname) { + String name = classname.substring(0, classname.length() - "Service".length()); + return toApiFilename(name); + } + + private String getModelnameFromModelFilename(String filename) { + String name = filename.substring((modelPackage() + "/").length()); + return camelize(name); + } + +} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/ApiServiceBinder.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/ApiServiceBinder.mustache new file mode 100644 index 000000000000..0026933c69c8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/ApiServiceBinder.mustache @@ -0,0 +1,20 @@ +import {interfaces} from "inversify"; + +{{#apiInfo}} +{{#apis}} +import { {{classname}} } from './{{importPath}}'; +{{#withInterfaces}} +import { {{classname}}Interface } from './{{importPath}}Interface'; +{{/withInterfaces}} +{{/apis}} +{{/apiInfo}} + +export class ApiServiceBinder { + public static with(container: interfaces.Container) { + {{#apiInfo}} + {{#apis}} + container.bind<{{classname}}{{#withInterfaces}}Interface{{/withInterfaces}}>("{{classname}}").to({{classname}}).inSingletonScope(); + {{/apis}} + {{/apiInfo}} + } +} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/Headers.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/Headers.mustache new file mode 100644 index 000000000000..0fa7760e01ea --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/Headers.mustache @@ -0,0 +1,3 @@ +export interface Headers { + [index:string]: string +} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpClient.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpClient.mustache new file mode 100644 index 000000000000..64fe12a30452 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpClient.mustache @@ -0,0 +1,63 @@ +import IHttpClient from "./IHttpClient"; +import { Observable } from "rxjs/Observable"; +import "whatwg-fetch"; +import HttpResponse from "./HttpResponse"; +import {injectable} from "inversify"; +import "rxjs/add/observable/fromPromise"; +import { Headers } from "./Headers"; + +@injectable() +class HttpClient implements IHttpClient { + + get(url:string, headers?: Headers):Observable { + return this.performNetworkCall(url, "get", undefined, headers); + } + + post(url: string, body: {}|FormData, headers?: Headers): Observable { + return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + put(url: string, body: {}, headers?: Headers): Observable { + return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + delete(url: string, headers?: Headers): Observable { + return this.performNetworkCall(url, "delete", undefined, headers); + } + + private getJsonBody(body: {}|FormData) { + return !(body instanceof FormData) ? JSON.stringify(body) : body; + } + + private addJsonHeaders(headers: Headers) { + return Object.assign({}, { + "Accept": "application/json", + "Content-Type": "application/json" + }, headers); + }; + + private performNetworkCall(url: string, method: string, body?: any, headers?: Headers): Observable { + let promise = window.fetch(url, { + method: method, + body: body, + headers: headers + }).then(response => { + let headers: Headers = {}; + response.headers.forEach((value, name) => { + headers[name.toString().toLowerCase()] = value; + }); + return response.text().then(text => { + let contentType = headers["content-type"] || ""; + let payload = contentType.match("application/json") ? JSON.parse(text) : text; + let httpResponse = new HttpResponse(payload, response.status, headers); + + if (response.status >= 400) + throw httpResponse; + return httpResponse; + }); + }); + return Observable.fromPromise(promise); + } +} + +export default HttpClient \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpResponse.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpResponse.mustache new file mode 100644 index 000000000000..411240cde2bd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpResponse.mustache @@ -0,0 +1,8 @@ +import { Headers } from "./Headers" + +class HttpResponse { + constructor(public response: T, public status:number, public headers?: Headers) { + } +} + +export default HttpResponse \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/IAPIConfiguration.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/IAPIConfiguration.mustache new file mode 100644 index 000000000000..2364e83e6cb3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/IAPIConfiguration.mustache @@ -0,0 +1,8 @@ +export interface IAPIConfiguration { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/IHttpClient.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/IHttpClient.mustache new file mode 100644 index 000000000000..22d9e07c903e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/IHttpClient.mustache @@ -0,0 +1,12 @@ +import { Observable } from "rxjs/Observable"; +import HttpResponse from "./HttpResponse"; +import { Headers } from "./Headers"; + +interface IHttpClient { + get(url:string, headers?: Headers):Observable + post(url:string, body:{}|FormData, headers?: Headers):Observable + put(url:string, body:{}, headers?: Headers):Observable + delete(url:string, headers?: Headers):Observable +} + +export default IHttpClient \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/README.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/README.mustache new file mode 100644 index 000000000000..4da4e854d960 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/README.mustache @@ -0,0 +1,74 @@ +## {{npmName}}@{{npmVersion}} + +### Building + +To build an compile the typescript sources to javascript use: +``` +npm install +npm run build +``` + +### publishing + +First build the package than run ```npm publish``` + +### consuming + +navigate to the folder of your consuming project and run one of next commando's. + +_published:_ + +``` +npm install {{npmName}}@{{npmVersion}} --save +``` + +_unPublished (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE --save +``` + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE: +``` +npm link +``` + +In your project: +``` +npm link {{npmName}}@{{npmVersion}} +``` + +## Requirements +Services require a `IHttpClient` and a `IApiConfiguration`. The `IHttpClient` is necessary to manage http's call and with the `IApiConfiguration` you can provide settings for the Authentication. +For the sake of simplicity an implementation of `IHttpClient` is already provided, but if you want you can override it. +For these reasons you have to manually bind these two services: + +```typescript +let container = new Container(); +container.bind("IApiHttpClient").to(HttpClient).inSingletonScope(); +container.bind("IApiConfiguration").to(ApiConfiguration).inSingletonScope(); +``` + + +## Services Binding +To bind all the generated services you can use `ApiServiceBinder`. + +```typescript +ApiServiceBinder.with(container); +``` + +## Final result + +```typescript +let container = new Container(); +container.bind("IApiHttpClient").to(HttpClient).inSingletonScope(); +container.bind("IApiConfiguration").to(ApiConfiguration).inSingletonScope(); +ApiServiceBinder.with(container); +``` + + + + + diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/api.service.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/api.service.mustache new file mode 100644 index 000000000000..259583755766 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/api.service.mustache @@ -0,0 +1,180 @@ +{{>licenseInfo}} +/* tslint:disable:no-unused-variable member-ordering */ + +import { Observable } from "rxjs/Observable"; +import 'rxjs/add/operator/map'; +import 'rxjs/add/operator/toPromise'; +import IHttpClient from "../IHttpClient"; +import { inject, injectable } from "inversify"; +import { IAPIConfiguration } from "../IAPIConfiguration"; +import { Headers } from "../Headers"; +import HttpResponse from "../HttpResponse"; + +{{#imports}} +import { {{classname}} } from '../{{filename}}'; +{{/imports}} + +import { COLLECTION_FORMATS } from '../variables'; +{{#withInterfaces}} +import { {{classname}}Interface } from './{{classname}}Interface'; +{{/withInterfaces}} + +{{#operations}} + +{{#description}} +/** + * {{&description}} + */ +{{/description}} + +@injectable() +{{#withInterfaces}} +export class {{classname}} implements {{classname}}Interface { +{{/withInterfaces}} +{{^withInterfaces}} +export class {{classname}} { +{{/withInterfaces}} + private basePath: string = '{{{basePath}}}'; + + constructor(@inject("IApiHttpClient") private httpClient: IHttpClient, + @inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) { + if(this.APIConfiguration.basePath) + this.basePath = this.APIConfiguration.basePath; + } +{{#operation}} + + /** + * {{summary}} + * {{notes}} + {{#allParams}}* @param {{paramName}} {{description}} + {{/allParams}}{{#useHttpClient}}* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress.{{/useHttpClient}} + */ + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'body', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>; + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'response', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}>; + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe: any = 'body', headers: Headers = {}): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}} { +{{#allParams}} +{{#required}} + if (!{{paramName}}){ + throw new Error('Required parameter {{paramName}} was null or undefined when calling {{nickname}}.'); + } + +{{/required}} +{{/allParams}} +{{#hasQueryParams}} + let queryParameters: string[] = []; +{{#queryParams}} + {{#isListContainer}} + if ({{paramName}}) { + {{#isCollectionFormatMulti}} + {{paramName}}.forEach((element) => { + queryParameters.push("{{paramName}}="+encodeURIComponent(String({{paramName}}))); + }) + {{/isCollectionFormatMulti}} + {{^isCollectionFormatMulti}} + queryParameters.push("{{paramName}}="+encodeURIComponent({{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']))); + {{/isCollectionFormatMulti}} + } + {{/isListContainer}} + {{^isListContainer}} + if ({{paramName}} !== undefined) { + {{#isDateTime}} + queryParameters.push("{{paramName}}="+encodeURIComponent({{paramName}}.toISOString())); + {{/isDateTime}} + {{^isDateTime}} + queryParameters.push("{{paramName}}="+encodeURIComponent(String({{paramName}}))); + {{/isDateTime}} + } + {{/isListContainer}} +{{/queryParams}} + +{{/hasQueryParams}} +{{#headerParams}} + {{#isListContainer}} + if ({{paramName}}) { + headers['{{baseName}}'] = {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']); + } + {{/isListContainer}} + {{^isListContainer}} + if ({{paramName}}) { + headers['{{baseName}}'] = String({{paramName}}); + } + {{/isListContainer}} + +{{/headerParams}} +{{#authMethods}} + // authentication ({{name}}) required +{{#isApiKey}} +{{#isKeyInHeader}} + if (this.APIConfiguration.apiKeys["{{keyParamName}}"]) { + headers['{{keyParamName}}'] = this.APIConfiguration.apiKeys["{{keyParamName}}"]; + } +{{/isKeyInHeader}} +{{#isKeyInQuery}} + if (this.APIConfiguration.apiKeys["{{keyParamName}}"]) { + queryParameters.push("{{paramName}}="+encodeURIComponent(String(this.APIConfiguration.apiKeys["{{keyParamName}}"]))); + } +{{/isKeyInQuery}} +{{/isApiKey}} +{{#isBasic}} + if (this.APIConfiguration.username || this.APIConfiguration.password) { + headers['Authorization'] = btoa(this.APIConfiguration.username + ':' + this.APIConfiguration.password); + } +{{/isBasic}} +{{#isOAuth}} + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } +{{/isOAuth}} +{{/authMethods}} + {{^produces}} + headers['Accept'] = 'application/json'; + {{/produces}} + {{#produces.0}} + headers['Accept'] = '{{{mediaType}}}'; + {{/produces.0}} +{{#bodyParam}} + {{^consumes}} + headers['Content-Type'] = 'application/json'; + {{/consumes}} + {{#consumes.0}} + headers['Content-Type'] = '{{{mediaType}}}'; + {{/consumes.0}} +{{/bodyParam}} + +{{#hasFormParams}} + let formData: FormData = new FormData(); + headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; +{{#formParams}} + {{#isListContainer}} + if ({{paramName}}) { + {{#isCollectionFormatMulti}} + {{paramName}}.forEach((element) => { + formData.append('{{baseName}}', element); + }) + {{/isCollectionFormatMulti}} + {{^isCollectionFormatMulti}} + formData.append('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])); + {{/isCollectionFormatMulti}} + } + {{/isListContainer}} + {{^isListContainer}} + if ({{paramName}} !== undefined) { + formData.append('{{baseName}}', {{paramName}}); + } + {{/isListContainer}} +{{/formParams}} + +{{/hasFormParams}} + const response: Observable> = this.httpClient.{{httpMethod}}(`${this.basePath}{{{path}}}{{#hasQueryParams}}?${queryParameters.join('&')}{{/hasQueryParams}}`{{#bodyParam}}, {{paramName}} {{/bodyParam}}{{#hasFormParams}}, body{{/hasFormParams}}, headers); + if (observe == 'body') { + return response.map(httpResponse => <{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>(httpResponse.response)){{#usePromise}}.toPromise(){{/usePromise}}; + } + return response{{#usePromise}}.toPromise(){{/usePromise}}; + } + +{{/operation}}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/apiInterface.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/apiInterface.mustache new file mode 100644 index 000000000000..cb31c6396b9e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/apiInterface.mustache @@ -0,0 +1,26 @@ +{{>licenseInfo}} +import { Headers } from "../Headers"; +import { Observable } from "rxjs/Observable"; +import * as models from "../model/models"; +import HttpResponse from "../HttpResponse"; + +{{#operations}} + +{{#description}} + /** + * {{&description}} + */ +{{/description}} +export interface {{classname}}Interface { +{{#operation}} + /** + * {{summary}} + * {{notes}} + {{#allParams}}* @param {{paramName}} {{description}} + {{/allParams}}*/ + + {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'body', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>; + {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'response', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}>; +{{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/apis.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/apis.mustache new file mode 100644 index 000000000000..3d49b9488b48 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/apis.mustache @@ -0,0 +1,5 @@ +{{#apiInfo}} +{{#apis}} +export * from './{{ classFilename }}'; +{{/apis}} +{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/git_push.sh.mustache new file mode 100755 index 000000000000..a2d752348373 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/git_push.sh.mustache @@ -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 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + 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/modules/swagger-codegen/src/main/resources/typescript-inversify/gitignore b/modules/swagger-codegen/src/main/resources/typescript-inversify/gitignore new file mode 100644 index 000000000000..23c3bdf9c9be --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/gitignore @@ -0,0 +1,6 @@ +wwwroot/*.js +node_modules +typings +dist +.vscode +.idea \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/index.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/index.mustache new file mode 100644 index 000000000000..54e1715c1e18 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/index.mustache @@ -0,0 +1,7 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './IAPIConfiguration'; +export * from './ApiServiceBinder'; +export * from './IHttpClient'; +export * from './HttpClient'; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/licenseInfo.mustache new file mode 100644 index 000000000000..7d61c4ee0550 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/model.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/model.mustache new file mode 100644 index 000000000000..0b93ad2998f0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/model.mustache @@ -0,0 +1,16 @@ +{{>licenseInfo}} +{{#models}} +{{#model}} +{{#tsImports}} +import { {{classname}} } from './{{filename}}'; +{{/tsImports}} + + +{{#description}} +/** + * {{{description}}} + */ +{{/description}} +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#isAlias}}{{>modelAlias}}{{/isAlias}}{{^isAlias}}{{#taggedUnions}}{{>modelTaggedUnion}}{{/taggedUnions}}{{^taggedUnions}}{{>modelGeneric}}{{/taggedUnions}}{{/isAlias}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelAlias.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelAlias.mustache new file mode 100644 index 000000000000..c1c6bf7a5da6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelAlias.mustache @@ -0,0 +1 @@ +export type {{classname}} = {{dataType}}; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelEnum.mustache new file mode 100644 index 000000000000..932d3c0fb471 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelEnum.mustache @@ -0,0 +1,9 @@ +export type {{classname}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}}; + +export const {{classname}} = { +{{#allowableValues}} +{{#enumVars}} + {{name}}: {{{value}}} as {{classname}}{{^-last}},{{/-last}} +{{/enumVars}} +{{/allowableValues}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGeneric.mustache new file mode 100644 index 000000000000..a4248ea3da0f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGeneric.mustache @@ -0,0 +1,10 @@ +export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ {{>modelGenericAdditionalProperties}} +{{#vars}} + {{#description}} + /** + * {{{description}}} + */ + {{/description}} + {{#isReadOnly}}readonly {{/isReadOnly}}{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; +{{/vars}} +}{{>modelGenericEnums}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache new file mode 100644 index 000000000000..e6499ce9d63f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache @@ -0,0 +1,5 @@ +{{#additionalPropertiesType}} + + [key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}}; + +{{/additionalPropertiesType}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericEnums.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericEnums.mustache new file mode 100644 index 000000000000..432020b726fa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericEnums.mustache @@ -0,0 +1,16 @@ +{{#hasEnums}} + +export namespace {{classname}} { +{{#vars}} + {{#isEnum}} + export type {{enumName}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}}; + export const {{enumName}} = { + {{#allowableValues}} + {{#enumVars}} + {{name}}: {{{value}}} as {{enumName}}{{^-last}},{{/-last}} + {{/enumVars}} + {{/allowableValues}} + } + {{/isEnum}} +{{/vars}} +}{{/hasEnums}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelTaggedUnion.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelTaggedUnion.mustache new file mode 100644 index 000000000000..cd7d1c8b936a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelTaggedUnion.mustache @@ -0,0 +1,21 @@ +{{#discriminator}} +export type {{classname}} = {{#children}}{{^-first}} | {{/-first}}{{classname}}{{/children}}; +{{/discriminator}} +{{^discriminator}} +{{#parent}} +export interface {{classname}} { {{>modelGenericAdditionalProperties}} +{{#allVars}} + {{#description}} + /** + * {{{description}}} + */ + {{/description}} + {{name}}{{^required}}?{{/required}}: {{#discriminatorValue}}'{{discriminatorValue}}'{{/discriminatorValue}}{{^discriminatorValue}}{{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}{{/discriminatorValue}}; +{{/allVars}} +} +{{>modelGenericEnums}} +{{/parent}} +{{^parent}} +{{>modelGeneric}} +{{/parent}} +{{/discriminator}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/models.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/models.mustache new file mode 100644 index 000000000000..02a39c248c4d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/models.mustache @@ -0,0 +1,5 @@ +{{#models}} +{{#model}} +export * from './{{{ classFilename }}}'; +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/package.mustache new file mode 100644 index 000000000000..9733f2058a51 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/package.mustache @@ -0,0 +1,29 @@ +{ + "name": "{{{npmName}}}", + "version": "{{{npmVersion}}}", + "description": "swagger client for {{{npmName}}}", + "author": "Swagger Codegen Contributors", + "keywords": [ + "swagger-client" + ], + "license": "Unlicense", + "main": "dist/index.js", + "typings": "dist/index.d.ts", + "scripts": { + "build": "tsc --outDir dist/", + "postinstall": "npm run build" + }, + "dependencies": { + "inversify": "^4.3.0", + "rxjs": "~5.5.7", + "whatwg-fetch": "~2.0.1", + "reflect-metadata": "0.1.8" + }, + "devDependencies": { + }{{#npmRepository}},{{/npmRepository}} +{{#npmRepository}} + "publishConfig": { + "registry": "{{{npmRepository}}}" + } +{{/npmRepository}} +} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/tsconfig.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/tsconfig.mustache new file mode 100644 index 000000000000..3ed5f2c0b100 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/tsconfig.mustache @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}", + "module": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}commonjs{{/supportsES6}}", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./dist", + "noLib": false, + "declaration": true, + "lib": [ "es6", "dom" ] + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] +} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/variables.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/variables.mustache new file mode 100644 index 000000000000..5d3805255c2e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/variables.mustache @@ -0,0 +1,6 @@ +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptInversifyClientOptionsProvider.java similarity index 57% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptInversifyClientOptionsProvider.java index 8ca58de536cf..191cd6788c34 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptInversifyClientOptionsProvider.java @@ -1,41 +1,44 @@ -package org.openapitools.codegen.options; +package io.swagger.codegen.options; import com.google.common.collect.ImmutableMap; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.TypeScriptAngularClientCodegen; +import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen; import java.util.Map; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; - - -public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { +public class TypeScriptInversifyClientOptionsProvider implements OptionsProvider { public static final String SUPPORTS_ES6_VALUE = "false"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; - private static final String NMP_NAME = "npmName"; private static final String NMP_VERSION = "1.1.2"; private static final String NPM_REPOSITORY = "https://registry.npmjs.org"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + public static final String USE_PROMISE = "false"; + + @Override public String getLanguage() { - return "typescript-node"; + return "typescript-inversify"; } @Override public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) - .put(TypeScriptAngularClientCodegen.NPM_NAME, NMP_NAME) - .put(TypeScriptAngularClientCodegen.NPM_VERSION, NMP_VERSION) - .put(TypeScriptAngularClientCodegen.SNAPSHOT, Boolean.FALSE.toString()) - .put(TypeScriptAngularClientCodegen.NPM_REPOSITORY, NPM_REPOSITORY) + .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) + .put(TypeScriptInversifyClientCodegen.NPM_NAME, NMP_NAME) + .put(TypeScriptInversifyClientCodegen.NPM_VERSION, NMP_VERSION) + .put(TypeScriptInversifyClientCodegen.SNAPSHOT, Boolean.FALSE.toString()) + .put(TypeScriptInversifyClientCodegen.WITH_INTERFACES, Boolean.FALSE.toString()) + .put(TypeScriptInversifyClientCodegen.TAGGED_UNIONS, Boolean.FALSE.toString()) + .put(TypeScriptInversifyClientCodegen.USE_PROMISE, Boolean.FALSE.toString()) + .put(TypeScriptInversifyClientCodegen.NPM_REPOSITORY, NPM_REPOSITORY) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyClientOptionsTest.java new file mode 100644 index 000000000000..2aee4c61b5c8 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyClientOptionsTest.java @@ -0,0 +1,36 @@ +package io.swagger.codegen.typescript.typescriptinversify; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen; +import io.swagger.codegen.options.TypeScriptInversifyClientOptionsProvider; +import mockit.Expectations; +import mockit.Tested; + +public class TypeScriptInversifyClientOptionsTest extends AbstractOptionsTest { + + @Tested + private TypeScriptInversifyClientCodegen clientCodegen; + + public TypeScriptInversifyClientOptionsTest() { + super(new TypeScriptInversifyClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptInversifyClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setModelPropertyNaming(TypeScriptInversifyClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + times = 1; + clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptInversifyClientOptionsProvider.SUPPORTS_ES6_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyModelTest.java similarity index 91% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyModelTest.java index 3544daa9db82..986f4b6956a5 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyModelTest.java @@ -1,14 +1,14 @@ -package org.openapitools.codegen.typescript.typescriptangular; +package io.swagger.codegen.typescript.typescriptinversify; +import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen; import org.testng.Assert; import org.testng.annotations.Test; import com.google.common.collect.Sets; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; import io.swagger.models.ArrayModel; import io.swagger.models.Model; import io.swagger.models.ModelImpl; @@ -20,7 +20,7 @@ import io.swagger.models.properties.StringProperty; @SuppressWarnings("static-method") -public class TypeScriptAngularModelTest { +public class TypeScriptInversifyModelTest { @Test(description = "convert a simple TypeScript Angular model") public void simpleModelTest() { @@ -32,7 +32,7 @@ public void simpleModelTest() { .property("birthDate", new DateProperty()) .required("id") .required("name"); - final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); @@ -90,7 +90,7 @@ public void listPropertyTest() { .property("id", new LongProperty()) .property("urls", new ArrayProperty().items(new StringProperty())) .required("id"); - final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); @@ -123,7 +123,7 @@ public void complexPropertyTest() { final Model model = new ModelImpl() .description("a sample model") .property("children", new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); @@ -147,7 +147,7 @@ public void complexListPropertyTest() { .description("a sample model") .property("children", new ArrayProperty() .items(new RefProperty("#/definitions/Children"))); - final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); @@ -170,7 +170,7 @@ public void arrayModelTest() { final Model model = new ArrayModel() .description("an array model") .items(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); @@ -184,7 +184,7 @@ public void mapModelTest() { final Model model = new ModelImpl() .description("a map model") .additionalProperties(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypescriptAngularArrayAndObjectIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyArrayAndObjectIntegrationTest.java similarity index 56% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypescriptAngularArrayAndObjectIntegrationTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyArrayAndObjectIntegrationTest.java index b8e694c7cf69..6dbc175923bc 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypescriptAngularArrayAndObjectIntegrationTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyArrayAndObjectIntegrationTest.java @@ -1,18 +1,18 @@ -package org.openapitools.codegen.typescript.typescriptangular; +package io.swagger.codegen.typescript.typescriptinversify; import java.util.HashMap; import java.util.Map; -import org.openapitools.codegen.AbstractIntegrationTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; -import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; +import io.swagger.codegen.AbstractIntegrationTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen; +import io.swagger.codegen.testutils.IntegrationTestPathsConfig; -public class TypescriptAngularArrayAndObjectIntegrationTest extends AbstractIntegrationTest { +public class TypescriptInversifyArrayAndObjectIntegrationTest extends AbstractIntegrationTest { @Override protected CodegenConfig getCodegenConfig() { - return new TypeScriptAngularClientCodegen(); + return new TypeScriptInversifyClientCodegen(); } @Override diff --git a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypescriptAngularPestoreIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyPestoreIntegrationTest.java similarity index 56% rename from modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypescriptAngularPestoreIntegrationTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyPestoreIntegrationTest.java index f4f942ddc4ea..de6cc5b5c515 100644 --- a/modules/openapi-generator/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypescriptAngularPestoreIntegrationTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyPestoreIntegrationTest.java @@ -1,18 +1,18 @@ -package org.openapitools.codegen.typescript.typescriptangular; +package io.swagger.codegen.typescript.typescriptinversify; import java.util.HashMap; import java.util.Map; -import org.openapitools.codegen.AbstractIntegrationTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; -import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; +import io.swagger.codegen.AbstractIntegrationTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen; +import io.swagger.codegen.testutils.IntegrationTestPathsConfig; -public class TypescriptAngularPestoreIntegrationTest extends AbstractIntegrationTest { +public class TypescriptInversifyPestoreIntegrationTest extends AbstractIntegrationTest { @Override protected CodegenConfig getCodegenConfig() { - return new TypeScriptAngularClientCodegen(); + return new TypeScriptInversifyClientCodegen(); } @Override @@ -21,6 +21,7 @@ protected Map configProperties() { properties.put("npmName", "petstore-integration-test"); properties.put("npmVersion", "1.0.3"); properties.put("snapshot", "false"); + properties.put("usePromise", "false"); return properties; } diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/GeneratorInputTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/GeneratorInputTest.java deleted file mode 100644 index 6b6b22fd6756..000000000000 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/GeneratorInputTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.swagger.generator; - -import io.swagger.generator.model.GeneratorInput; - -import org.testng.annotations.Test; - -@SuppressWarnings("static-method") -public class GeneratorInputTest { - - @Test(description = "write an object") - public void writeObjectTest() { - final GeneratorInput generatorInput = new GeneratorInput(); - generatorInput.setSwaggerUrl("http://petstore.swagger.io/v2/swagger.json"); - } -} diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java deleted file mode 100644 index c24307ea4fdb..000000000000 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java +++ /dev/null @@ -1,188 +0,0 @@ -package io.swagger.generator.online; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Function; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConfigLoader; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.languages.JavaClientCodegen; -import io.swagger.codegen.options.*; -import io.swagger.generator.exception.ApiException; -import io.swagger.generator.model.GeneratorInput; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import javax.annotation.Nullable; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.*; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotEquals; - -public class OnlineGeneratorOptionsTest { - private static final String OPTIONS_PROVIDER = "optionsProvider"; - - @DataProvider(name = OPTIONS_PROVIDER) - private static Object[][] listOptions() { - return new Object[][] { - {new AkkaScalaClientOptionsProvider()}, - {new AndroidClientOptionsProvider()}, - {new AsyncScalaClientOptionsProvider()}, - {new CSharpClientOptionsProvider()}, - {new CsharpDotNet2ClientOptionsProvider()}, - {new DartClientOptionsProvider()}, - {new FlashClienOptionsProvider()}, - {new JavaInflectorServerOptionsProvider()}, - { - new JavaOptionsProvider(), - new JavaOptionsProvider(ImmutableMap.of(CodegenConstants.LIBRARY, - JavaClientCodegen.RETROFIT_2)), - new JavaOptionsProvider( - ImmutableMap.of(CodegenConstants.LIBRARY, - JavaClientCodegen.RETROFIT_2, - JavaClientCodegen.USE_RX_JAVA, "true"))}, - {new JaxRSServerOptionsProvider()}, {new NodeJSServerOptionsProvider()}, - {new ObjcClientOptionsProvider()}, {new PerlClientOptionsProvider()}, - {new PhpClientOptionsProvider()}, {new PythonClientOptionsProvider()}, - {new Qt5CPPOptionsProvider()}, {new RubyClientOptionsProvider()}, - {new ScalaClientOptionsProvider()}, {new ScalatraServerOptionsProvider()}, - {new SilexServerOptionsProvider()}, {new SinatraServerOptionsProvider()}, - {new SlimFrameworkServerOptionsProvider()}, {new SpringOptionsProvider()}, - {new StaticDocOptionsProvider()}, {new StaticHtmlOptionsProvider()}, - {new SwaggerOptionsProvider()}, {new SwaggerYamlOptionsProvider()}, - {new SwiftOptionsProvider()}, {new TizenClientOptionsProvider()}, - {new TypeScriptAngularClientOptionsProvider()}, - {new TypeScriptNodeClientOptionsProvider()}, {new LumenServerOptionsProvider()}}; - } - - @Test(dataProvider = OPTIONS_PROVIDER) - public void generateOptionsTest(OptionsProvider provider) throws ApiException, IOException { - final GeneratorInput input = new GeneratorInput(); - final HashMap options = convertOptions(provider); - - final Maps.EntryTransformer transformer = - new Maps.EntryTransformer() { - @Override - public String transformEntry(String key, InvocationCounter value) { - return value.getValue(); - } - }; - - input.setOptions(Maps.transformEntries(options, transformer)); - final ObjectMapper mapper = new ObjectMapper(); - input.setSpec(mapper.readTree(loadClassResource(getClass(), "petstore.json"))); - String outputFilename; - if (provider.isServer()) { - outputFilename = Generator.generateServer(provider.getLanguage(), input); - } else { - outputFilename = Generator.generateClient(provider.getLanguage(), input); - } - final File dir = new File(new File(outputFilename).getParent()); - - try { - FileUtils.deleteDirectory(dir); - } catch (Exception e) { // directory can't be deleted for some reasons - e.printStackTrace(); - } - for (InvocationCounter option : options.values()) { - assertNotEquals(option.getCounter(), 0, - String.format("Option \"%s\" wasn't processed.", option.getValue())); - } - } - - private static HashMap convertOptions(OptionsProvider provider) { - HashMap options = new HashMap(); - for (Map.Entry entry : provider.createOptions().entrySet()) { - options.put(entry.getKey(), new InvocationCounter(entry.getValue())); - } - return options; - } - - private static String loadClassResource(Class cls, String name) throws IOException { - InputStream in = null; - try { - in = cls.getClassLoader().getResourceAsStream(name); - return IOUtils.toString(in, StandardCharsets.UTF_8); - } finally { - IOUtils.closeQuietly(in); - } - } - - private static class InvocationCounter { - private String value; - private int counter; - - public InvocationCounter(String value) { - this.value = value; - } - - public int getCounter() { - return counter; - } - - public String getValue() { - ++counter; - return value; - } - } - - @Test(dataProvider = OPTIONS_PROVIDER) - public static void getOptionsTest(OptionsProvider provider) throws ApiException { - final Map opts = Generator.getOptions(provider.getLanguage()); - - final Function cliOptionWrapper = - new Function() { - @Nullable - @Override - public CliOptionProxy apply(@Nullable CliOption option) { - return new CliOptionProxy(option); - } - }; - - final List actual = - Lists.transform(new ArrayList(opts.values()), cliOptionWrapper); - final List expected = - Lists.transform(CodegenConfigLoader.forName(provider.getLanguage()).cliOptions(), - cliOptionWrapper); - assertEquals(actual, expected); - } - - protected static class CliOptionProxy { - private final CliOption wrapped; - - public CliOptionProxy(CliOption wrapped) { - this.wrapped = wrapped; - } - - public CliOption getWrapped() { - return wrapped; - } - - @Override - public int hashCode() { - return Objects.hash(wrapped.getOpt(), wrapped.getDescription(), wrapped.getType(), - wrapped.getDefault(), wrapped.getEnum()); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof CliOptionProxy) { - final CliOption that = ((CliOptionProxy) obj).getWrapped(); - return Objects.equals(wrapped.getOpt(), that.getOpt()) - && Objects.equals(wrapped.getDescription(), that.getDescription()) - && Objects.equals(wrapped.getType(), that.getType()) - && Objects.equals(wrapped.getDefault(), that.getDefault()) - && Objects.equals(wrapped.getEnum(), that.getEnum()); - } - return false; - } - } -} diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java deleted file mode 100644 index e3ad18ecbdcb..000000000000 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.swagger.generator.online; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.languages.JavaClientCodegen; -import io.swagger.codegen.options.JavaOptionsProvider; -import io.swagger.generator.exception.ApiException; - -import org.testng.annotations.Test; - -import java.util.Map; - -@SuppressWarnings("static-method") -public class OnlineJavaClientOptionsTest { - - @Test - public void getOptionsTest() throws ApiException { - final Map options = - Generator.getOptions(new JavaOptionsProvider().getLanguage()); - assertNotNull(options); - final CliOption opt = options.get(CodegenConstants.LIBRARY); - assertNotNull(opt); - assertEquals(opt.getDefault(), "okhttp-gson"); - } -} diff --git a/modules/swagger-generator/src/test/resources/petstore.json b/modules/swagger-generator/src/test/resources/petstore.json deleted file mode 100644 index 1617f8d0ae67..000000000000 --- a/modules/swagger-generator/src/test/resources/petstore.json +++ /dev/null @@ -1,1030 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", - "version": "1.0.0", - "title": "Swagger Petstore", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "email": "apiteam@swagger.io" - }, - "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", - "externalDocs": { - "description": "Find out more", - "url": "http://swagger.io" - } - }, - { - "name": "store", - "description": "Access to Petstore orders" - }, - { - "name": "user", - "description": "Operations about user", - "externalDocs": { - "description": "Find out more about our store", - "url": "http://swagger.io" - } - } - ], - "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" - ] - } - ] - } - }, - "/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" - }, - { - "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" - } - ], - "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.0, - "minimum": 1.0, - "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", - "minimum": 1.0 - } - ], - "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": { - "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" - } - }, - "User": { - "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" - } - }, - "Category": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "xml": { - "name": "Category" - } - }, - "Tag": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "xml": { - "name": "Tag" - } - }, - "ApiResponse": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "type": { - "type": "string" - }, - "message": { - "type": "string" - } - } - }, - "Pet": { - "type": "object", - "required": [ - "name", - "photoUrls" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "category": { - "$ref": "#/definitions/Category" - }, - "name": { - "type": "string", - "example": "doggie" - }, - "photoUrls": { - "type": "array", - "xml": { - "name": "photoUrl", - "wrapped": true - }, - "items": { - "type": "string" - } - }, - "tags": { - "type": "array", - "xml": { - "name": "tag", - "wrapped": true - }, - "items": { - "$ref": "#/definitions/Tag" - } - }, - "status": { - "type": "string", - "description": "pet status in the store", - "enum": [ - "available", - "pending", - "sold" - ] - } - }, - "xml": { - "name": "Pet" - } - } - }, - "externalDocs": { - "description": "Find out more about Swagger", - "url": "http://swagger.io" - } -} diff --git a/pom.xml b/pom.xml index f1b0b74dd185..e4310d42675c 100644 --- a/pom.xml +++ b/pom.xml @@ -834,7 +834,6 @@ samples/client/petstore/php/SwaggerClient-php - samples/client/petstore/ruby samples/client/petstore/scala samples/client/petstore/akka-scala samples/client/petstore/javascript @@ -854,14 +853,15 @@ samples/client/petstore/typescript-angular-v4/npm samples/client/petstore/typescript-angular-v4.3/npm + samples/client/petstore/ruby modules/openapi-generator modules/openapi-generator-cli - + modules/openapi-generator-maven-plugin + modules/openapi-generator-online target/site @@ -925,10 +925,10 @@ - 1.0.34 + 2.0.0-SNAPSHOT + 2.0.0 2.11.1 3.3.0 - 1.5.18 2.4 1.2 4.8.1 @@ -937,7 +937,7 @@ 3.4 1.7.12 3.2.1 - 1.12 + 1.14 6.9.6 2.19.1 1.25 diff --git a/pom.xml.bash b/pom.xml.bash index d691f51be634..c79f0e5796f2 100644 --- a/pom.xml.bash +++ b/pom.xml.bash @@ -909,10 +909,10 @@ - 1.0.34 + 2.0.0-SNAPSHOT + 2.0.0 2.11.1 3.3.0 - 1.5.18 2.4 1.2 4.8.1 diff --git a/pom.xml.circleci b/pom.xml.circleci index 73848cd47c6a..f4234888845a 100644 --- a/pom.xml.circleci +++ b/pom.xml.circleci @@ -6,16 +6,16 @@ 5 4.0.0 - io.swagger - swagger-codegen-project + org.openapitools + openapi-generator-project pom - swagger-codegen-project - 2.4.0-SNAPSHOT - https://github.com/swagger-api/swagger-codegen + openapi-genearator-project + 3.0.0-SNAPSHOT + https://github.com/openapitools/openapi-generator - scm:git:git@github.com:swagger-api/swagger-codegen.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator 2.2.0 @@ -34,14 +34,8 @@ github - https://github.com/swagger-api/swagger-codegen/issues + https://github.com/openapitools/openapi-generator/issues - - - swagger-swaggersocket - https://groups.google.com/forum/#!forum/swagger-swaggersocket - - Apache License 2.0 @@ -890,10 +884,10 @@ - modules/swagger-codegen - modules/swagger-codegen-cli - modules/swagger-codegen-maven-plugin - modules/swagger-generator + modules/openapi-generator + modules/openapi-generator-cli + modules/openapi-generator-maven-plugin + modules/openapi-generator-online target/site @@ -957,10 +951,10 @@ - 1.0.34 + 2.0.0-SNAPSHOT + 2.0.0 2.11.1 3.3.0 - 1.5.18 2.4 1.2 4.8.1 diff --git a/pom.xml.circleci.java7 b/pom.xml.circleci.java7 index eda93127cd79..5d8d1894067f 100644 --- a/pom.xml.circleci.java7 +++ b/pom.xml.circleci.java7 @@ -6,16 +6,16 @@ 5 4.0.0 - io.swagger - swagger-codegen-project + org.openapitools + openapi-generator-project pom - swagger-codegen-project + openapi-generator-project 2.4.0-SNAPSHOT - https://github.com/swagger-api/swagger-codegen + https://github.com/openapitools/openapi-generator - scm:git:git@github.com:swagger-api/swagger-codegen.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator 2.2.0 @@ -34,7 +34,7 @@ github - https://github.com/swagger-api/swagger-codegen/issues + https://github.com/openapitools/openapi-generator/issues @@ -872,10 +872,10 @@ - modules/swagger-codegen - modules/swagger-codegen-cli - modules/swagger-codegen-maven-plugin - modules/swagger-generator + modules/openapi-generator + modules/openapi-generator-cli + modules/openapi-generator-maven-plugin + modules/openapi-generator-online target/site @@ -939,10 +939,10 @@ - 1.0.34 + 2.0.0-SNAPSHOT + 2.0.0 2.11.1 3.3.0 - 1.5.18 2.4 1.2 4.8.1 diff --git a/pom.xml.ios b/pom.xml.ios index 82221e79e219..f50b0b0d83b5 100644 --- a/pom.xml.ios +++ b/pom.xml.ios @@ -917,10 +917,10 @@ - 1.0.34 + 2.0.0-SNAPSHOT + 2.0.0 2.11.1 3.3.0 - 1.5.18 2.4 1.2 4.8.1 diff --git a/pom.xml.shippable b/pom.xml.shippable index 18c51aa323e9..e6f811cd24db 100644 --- a/pom.xml.shippable +++ b/pom.xml.shippable @@ -5,16 +5,16 @@ 5 4.0.0 - io.swagger - swagger-codegen-project + org.openapitools + openapi-generator-project pom - swagger-codegen-project - 2.4.0-SNAPSHOT - https://github.com/swagger-api/swagger-codegen + openapi-generator-project + 3.0.0-SNAPSHOT + https://github.com/openapitools/openapi-generator - scm:git:git@github.com:swagger-api/swagger-codegen.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator @@ -30,14 +30,8 @@ github - https://github.com/swagger-api/swagger-codegen/issues + https://github.com/openapitools/openapi-generator/issues - - - swagger-swaggersocket - https://groups.google.com/forum/#!forum/swagger-swaggersocket - - Apache License 2.0 @@ -844,10 +838,10 @@ - modules/swagger-codegen - modules/swagger-codegen-cli - modules/swagger-codegen-maven-plugin - modules/swagger-generator + modules/openapi-generator + modules/openapi-generator-cli + modules/openapi-generator-maven-plugin + modules/openapi-generator-online target/site @@ -911,10 +905,10 @@ - 1.0.34 + 2.0.0-SNAPSHOT + 2.0.0 2.11.1 3.3.0 - 1.5.18 2.4 1.2 4.8.1 diff --git a/run-in-docker.sh b/run-in-docker.sh index 6777d9a31b56..31c477645033 100755 --- a/run-in-docker.sh +++ b/run-in-docker.sh @@ -15,4 +15,4 @@ docker run --rm -it \ -v "${PWD}:/gen" \ -v "${maven_cache_repo}:/var/maven/.m2/repository" \ --entrypoint /gen/docker-entrypoint.sh \ - maven:3-jdk-7 "$@" + maven:3-jdk-8 "$@" diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php index c3f4590bc51f..720eb97a8e53 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -271,7 +271,7 @@ public static function deserialize($data, $class, $httpHeaders = null) // determine file name if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { - $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . self::sanitizeFilename($match[1]); + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . DIRECTORY_SEPARATOR . self::sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } diff --git a/samples/client/petstore-security-test/typescript-fetch/api.ts b/samples/client/petstore-security-test/typescript-fetch/api.ts index 027bc9439100..d69e2ae751d1 100644 --- a/samples/client/petstore-security-test/typescript-fetch/api.ts +++ b/samples/client/petstore-security-test/typescript-fetch/api.ts @@ -191,7 +191,7 @@ export class FakeApi extends BaseAPI { /** * * @summary To test code injection *_/ ' \" =end -- \\r\\n \\n \\r - * @param {} [testCodeInjectEndRnNR] To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * @param {string} [testCodeInjectEndRnNR] To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof FakeApi diff --git a/samples/client/petstore-security-test/typescript-inversify/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-inversify/.swagger-codegen-ignore new file mode 100644 index 000000000000..c5fa491b4c55 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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-security-test/typescript-inversify/.swagger-codegen/VERSION b/samples/client/petstore-security-test/typescript-inversify/.swagger-codegen/VERSION new file mode 100644 index 000000000000..855ff9501eb8 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-inversify/ApiServiceBinder.ts b/samples/client/petstore-security-test/typescript-inversify/ApiServiceBinder.ts new file mode 100644 index 000000000000..60f8cd6fa5d2 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/ApiServiceBinder.ts @@ -0,0 +1,9 @@ +import {interfaces} from "inversify"; + +import { FakeService } from './api/fake.service'; + +export class ApiServiceBinder { + public static with(container: interfaces.Container) { + container.bind("FakeService").to(FakeService).inSingletonScope(); + } +} diff --git a/samples/client/petstore-security-test/typescript-inversify/Headers.ts b/samples/client/petstore-security-test/typescript-inversify/Headers.ts new file mode 100644 index 000000000000..0fa7760e01ea --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/Headers.ts @@ -0,0 +1,3 @@ +export interface Headers { + [index:string]: string +} diff --git a/samples/client/petstore-security-test/typescript-inversify/HttpClient.ts b/samples/client/petstore-security-test/typescript-inversify/HttpClient.ts new file mode 100644 index 000000000000..64fe12a30452 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/HttpClient.ts @@ -0,0 +1,63 @@ +import IHttpClient from "./IHttpClient"; +import { Observable } from "rxjs/Observable"; +import "whatwg-fetch"; +import HttpResponse from "./HttpResponse"; +import {injectable} from "inversify"; +import "rxjs/add/observable/fromPromise"; +import { Headers } from "./Headers"; + +@injectable() +class HttpClient implements IHttpClient { + + get(url:string, headers?: Headers):Observable { + return this.performNetworkCall(url, "get", undefined, headers); + } + + post(url: string, body: {}|FormData, headers?: Headers): Observable { + return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + put(url: string, body: {}, headers?: Headers): Observable { + return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + delete(url: string, headers?: Headers): Observable { + return this.performNetworkCall(url, "delete", undefined, headers); + } + + private getJsonBody(body: {}|FormData) { + return !(body instanceof FormData) ? JSON.stringify(body) : body; + } + + private addJsonHeaders(headers: Headers) { + return Object.assign({}, { + "Accept": "application/json", + "Content-Type": "application/json" + }, headers); + }; + + private performNetworkCall(url: string, method: string, body?: any, headers?: Headers): Observable { + let promise = window.fetch(url, { + method: method, + body: body, + headers: headers + }).then(response => { + let headers: Headers = {}; + response.headers.forEach((value, name) => { + headers[name.toString().toLowerCase()] = value; + }); + return response.text().then(text => { + let contentType = headers["content-type"] || ""; + let payload = contentType.match("application/json") ? JSON.parse(text) : text; + let httpResponse = new HttpResponse(payload, response.status, headers); + + if (response.status >= 400) + throw httpResponse; + return httpResponse; + }); + }); + return Observable.fromPromise(promise); + } +} + +export default HttpClient \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-inversify/HttpResponse.ts b/samples/client/petstore-security-test/typescript-inversify/HttpResponse.ts new file mode 100644 index 000000000000..411240cde2bd --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/HttpResponse.ts @@ -0,0 +1,8 @@ +import { Headers } from "./Headers" + +class HttpResponse { + constructor(public response: T, public status:number, public headers?: Headers) { + } +} + +export default HttpResponse \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-inversify/IAPIConfiguration.ts b/samples/client/petstore-security-test/typescript-inversify/IAPIConfiguration.ts new file mode 100644 index 000000000000..2364e83e6cb3 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/IAPIConfiguration.ts @@ -0,0 +1,8 @@ +export interface IAPIConfiguration { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; +} \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-inversify/IHttpClient.ts b/samples/client/petstore-security-test/typescript-inversify/IHttpClient.ts new file mode 100644 index 000000000000..22d9e07c903e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/IHttpClient.ts @@ -0,0 +1,12 @@ +import { Observable } from "rxjs/Observable"; +import HttpResponse from "./HttpResponse"; +import { Headers } from "./Headers"; + +interface IHttpClient { + get(url:string, headers?: Headers):Observable + post(url:string, body:{}|FormData, headers?: Headers):Observable + put(url:string, body:{}, headers?: Headers):Observable + delete(url:string, headers?: Headers):Observable +} + +export default IHttpClient \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-inversify/api/fake.service.ts b/samples/client/petstore-security-test/typescript-inversify/api/fake.service.ts new file mode 100644 index 000000000000..418d247b1561 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/api/fake.service.ts @@ -0,0 +1,62 @@ +/** + * Swagger 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 -- + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Observable } from "rxjs/Observable"; +import 'rxjs/add/operator/map'; +import 'rxjs/add/operator/toPromise'; +import IHttpClient from "../IHttpClient"; +import { inject, injectable } from "inversify"; +import { IAPIConfiguration } from "../IAPIConfiguration"; +import { Headers } from "../Headers"; +import HttpResponse from "../HttpResponse"; + + +import { COLLECTION_FORMATS } from '../variables'; + + + +@injectable() +export class FakeService { + private basePath: string = 'https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r'; + + constructor(@inject("IApiHttpClient") private httpClient: IHttpClient, + @inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) { + if(this.APIConfiguration.basePath) + this.basePath = this.APIConfiguration.basePath; + } + + /** + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + + */ + public testCodeInjectEndRnNR(testCodeInjectEndRnNR?: string, observe?: 'body', headers?: Headers): Observable; + public testCodeInjectEndRnNR(testCodeInjectEndRnNR?: string, observe?: 'response', headers?: Headers): Observable>; + public testCodeInjectEndRnNR(testCodeInjectEndRnNR?: string, observe: any = 'body', headers: Headers = {}): Observable { + headers['Accept'] = 'application/json'; + + let formData: FormData = new FormData(); + headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; + if (testCodeInjectEndRnNR !== undefined) { + formData.append('test code inject */ ' " =end -- \r\n \n \r', testCodeInjectEndRnNR); + } + + const response: Observable> = this.httpClient.put(`${this.basePath}/fake`, body, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + +} diff --git a/samples/client/petstore-security-test/typescript-inversify/model/modelReturn.ts b/samples/client/petstore-security-test/typescript-inversify/model/modelReturn.ts new file mode 100644 index 000000000000..515aa6eff6ae --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/model/modelReturn.ts @@ -0,0 +1,22 @@ +/** + * Swagger 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 -- + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +/** + * Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r + */ +export interface ModelReturn { + /** + * property description *_/ ' \" =end -- \\r\\n \\n \\r + */ + _return?: number; +} diff --git a/samples/client/petstore-security-test/typescript-inversify/variables.ts b/samples/client/petstore-security-test/typescript-inversify/variables.ts new file mode 100644 index 000000000000..5d3805255c2e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/variables.ts @@ -0,0 +1,6 @@ +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/petstore/clojure/.swagger-codegen/VERSION b/samples/client/petstore/clojure/.swagger-codegen/VERSION index 7fea99011a6f..855ff9501eb8 100644 --- a/samples/client/petstore/clojure/.swagger-codegen/VERSION +++ b/samples/client/petstore/clojure/.swagger-codegen/VERSION @@ -1 +1 @@ -2.2.3-SNAPSHOT \ No newline at end of file +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/clojure/git_push.sh b/samples/client/petstore/clojure/git_push.sh index ed374619b139..ae01b182ae9e 100644 --- a/samples/client/petstore/clojure/git_push.sh +++ b/samples/client/petstore/clojure/git_push.sh @@ -36,7 +36,7 @@ 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 crediential in your environment." + 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 diff --git a/samples/client/petstore/clojure/project.clj b/samples/client/petstore/clojure/project.clj index b30c4b0f3fbf..e8d9f50a2954 100644 --- a/samples/client/petstore/clojure/project.clj +++ b/samples/client/petstore/clojure/project.clj @@ -1,6 +1,6 @@ (defproject swagger-petstore "1.0.0" :description "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters" - :license {:name "Apache 2.0" + :license {:name "Apache-2.0" :url "http://www.apache.org/licenses/LICENSE-2.0.html"} :dependencies [[org.clojure/clojure "1.7.0"] [clj-http "3.6.0"] diff --git a/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj b/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj index 344ea3bb1f83..c2bdf016c73d 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj @@ -29,6 +29,7 @@ " ([pet-id ] (delete-pet-with-http-info pet-id nil)) ([pet-id {:keys [api-key ]}] + (check-required-params pet-id) (call-api "/pet/{petId}" :delete {:path-params {"petId" pet-id } :header-params {"api_key" api-key } @@ -91,6 +92,7 @@ "Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions" [pet-id ] + (check-required-params pet-id) (call-api "/pet/{petId}" :get {:path-params {"petId" pet-id } :header-params {} @@ -133,6 +135,7 @@ " ([pet-id ] (update-pet-with-form-with-http-info pet-id nil)) ([pet-id {:keys [name status ]}] + (check-required-params pet-id) (call-api "/pet/{petId}" :post {:path-params {"petId" pet-id } :header-params {} @@ -154,6 +157,7 @@ " ([pet-id ] (upload-file-with-http-info pet-id nil)) ([pet-id {:keys [additional-metadata ^File file ]}] + (check-required-params pet-id) (call-api "/pet/{petId}/uploadImage" :post {:path-params {"petId" pet-id } :header-params {} diff --git a/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj b/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj index 04d185a8086c..1a690e4a56cc 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj @@ -6,6 +6,7 @@ "Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors" [order-id ] + (check-required-params order-id) (call-api "/store/order/{orderId}" :delete {:path-params {"orderId" order-id } :header-params {} @@ -44,6 +45,7 @@ "Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions" [order-id ] + (check-required-params order-id) (call-api "/store/order/{orderId}" :get {:path-params {"orderId" order-id } :header-params {} diff --git a/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj b/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj index 26e3dffc6240..78fa5463a8ba 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj @@ -72,6 +72,7 @@ "Delete user This can only be done by the logged in user." [username ] + (check-required-params username) (call-api "/user/{username}" :delete {:path-params {"username" username } :header-params {} @@ -91,6 +92,7 @@ "Get user by user name " [username ] + (check-required-params username) (call-api "/user/{username}" :get {:path-params {"username" username } :header-params {} @@ -151,6 +153,7 @@ This can only be done by the logged in user." ([username ] (update-user-with-http-info username nil)) ([username {:keys [body ]}] + (check-required-params username) (call-api "/user/{username}" :put {:path-params {"username" username } :header-params {} diff --git a/samples/client/petstore/cpprest/.swagger-codegen/VERSION b/samples/client/petstore/cpprest/.swagger-codegen/VERSION index f9f7450d1359..096bf47efe31 100644 --- a/samples/client/petstore/cpprest/.swagger-codegen/VERSION +++ b/samples/client/petstore/cpprest/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/cpprest/ApiClient.cpp b/samples/client/petstore/cpprest/ApiClient.cpp index 868b78c85210..d571a95f5402 100644 --- a/samples/client/petstore/cpprest/ApiClient.cpp +++ b/samples/client/petstore/cpprest/ApiClient.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -61,6 +61,11 @@ utility::string_t ApiClient::parameterToString(float value) return utility::conversions::to_string_t(std::to_string(value)); } +utility::string_t ApiClient::parameterToString(double value) +{ + return utility::conversions::to_string_t(std::to_string(value)); +} + utility::string_t ApiClient::parameterToString(const utility::datetime &value) { return utility::conversions::to_string_t(value.to_string(utility::datetime::ISO_8601)); diff --git a/samples/client/petstore/cpprest/ApiClient.h b/samples/client/petstore/cpprest/ApiClient.h index 4b6877e04b3a..595b7047c5f1 100644 --- a/samples/client/petstore/cpprest/ApiClient.h +++ b/samples/client/petstore/cpprest/ApiClient.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -51,21 +51,10 @@ class ApiClient static utility::string_t parameterToString(int32_t value); static utility::string_t parameterToString(int64_t value); static utility::string_t parameterToString(float value); + static utility::string_t parameterToString(double value); static utility::string_t parameterToString(const utility::datetime &value); - template - static utility::string_t parameterToArrayString(std::vector value) - { - utility::stringstream_t ss; - - for( size_t i = 0; i < value.size(); i++) - { - if( i > 0) ss << utility::conversions::to_string_t(", "); - ss << ApiClient::parameterToString(value[i]); - } - - return ss.str(); - } + static utility::string_t parameterToString(const std::vector& value); pplx::task callApi( const utility::string_t& path, @@ -83,6 +72,20 @@ class ApiClient std::shared_ptr m_Configuration; }; +template +utility::string_t ApiClient::parameterToString(const std::vector& value) +{ + utility::stringstream_t ss; + + for( size_t i = 0; i < value.size(); i++) + { + if( i > 0) ss << utility::conversions::to_string_t(", "); + ss << ApiClient::parameterToString(value[i]); + } + + return ss.str(); +} + } } } diff --git a/samples/client/petstore/cpprest/ApiConfiguration.cpp b/samples/client/petstore/cpprest/ApiConfiguration.cpp index 5baa1e79483a..8451113e1252 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.cpp +++ b/samples/client/petstore/cpprest/ApiConfiguration.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/ApiConfiguration.h b/samples/client/petstore/cpprest/ApiConfiguration.h index d5d22d8fb66d..ae3c57f919b7 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.h +++ b/samples/client/petstore/cpprest/ApiConfiguration.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/ApiException.cpp b/samples/client/petstore/cpprest/ApiException.cpp index 92b13730ce9b..74be9f7916b9 100644 --- a/samples/client/petstore/cpprest/ApiException.cpp +++ b/samples/client/petstore/cpprest/ApiException.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/ApiException.h b/samples/client/petstore/cpprest/ApiException.h index b5dcdadb87c9..5dfd69846805 100644 --- a/samples/client/petstore/cpprest/ApiException.h +++ b/samples/client/petstore/cpprest/ApiException.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/HttpContent.cpp b/samples/client/petstore/cpprest/HttpContent.cpp index 5904c0371a62..99a84063a3ac 100644 --- a/samples/client/petstore/cpprest/HttpContent.cpp +++ b/samples/client/petstore/cpprest/HttpContent.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/HttpContent.h b/samples/client/petstore/cpprest/HttpContent.h index dcbd4868e842..97279dfdb6a2 100644 --- a/samples/client/petstore/cpprest/HttpContent.h +++ b/samples/client/petstore/cpprest/HttpContent.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/IHttpBody.h b/samples/client/petstore/cpprest/IHttpBody.h index 6d2a61bae3a7..e01b2d4af148 100644 --- a/samples/client/petstore/cpprest/IHttpBody.h +++ b/samples/client/petstore/cpprest/IHttpBody.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/JsonBody.cpp b/samples/client/petstore/cpprest/JsonBody.cpp index 5cde61314cd9..451fbf00cdb6 100644 --- a/samples/client/petstore/cpprest/JsonBody.cpp +++ b/samples/client/petstore/cpprest/JsonBody.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/JsonBody.h b/samples/client/petstore/cpprest/JsonBody.h index a8960d94ad83..5364e9b395b5 100644 --- a/samples/client/petstore/cpprest/JsonBody.h +++ b/samples/client/petstore/cpprest/JsonBody.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/ModelBase.cpp b/samples/client/petstore/cpprest/ModelBase.cpp index 984e9f6e0a6f..db9a66f25c58 100644 --- a/samples/client/petstore/cpprest/ModelBase.cpp +++ b/samples/client/petstore/cpprest/ModelBase.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/ModelBase.h b/samples/client/petstore/cpprest/ModelBase.h index b68b7898ad08..1ed9027765ee 100644 --- a/samples/client/petstore/cpprest/ModelBase.h +++ b/samples/client/petstore/cpprest/ModelBase.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -26,6 +26,8 @@ #include #include +#include + namespace io { namespace swagger { namespace client { @@ -53,6 +55,8 @@ class ModelBase static web::json::value toJson( int64_t value ); static web::json::value toJson( double value ); static web::json::value toJson( bool value ); + template + static web::json::value toJson(const std::vector& value); static int64_t int64_tFromJson(web::json::value& val); static int32_t int32_tFromJson(web::json::value& val); @@ -70,6 +74,8 @@ class ModelBase static std::shared_ptr toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); static std::shared_ptr toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); static std::shared_ptr toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + template + static std::shared_ptr toHttpContent( const utility::string_t& name, const std::vector& value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); static int64_t int64_tFromHttpContent(std::shared_ptr val); static int32_t int32_tFromHttpContent(std::shared_ptr val); @@ -86,6 +92,27 @@ class ModelBase static std::shared_ptr fromBase64( const utility::string_t& encoded ); }; +template +web::json::value ModelBase::toJson(const std::vector& value) { + std::vector ret; + for (auto& x : value) { + ret.push_back(toJson(x)); + } + + return web::json::value::array(ret); +} + +template +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const std::vector& value, const utility::string_t& contentType ) { + web::json::value json_array = ModelBase::toJson(value); + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(json_array.serialize()) ) ) ); + return content; +} + } } } diff --git a/samples/client/petstore/cpprest/MultipartFormData.cpp b/samples/client/petstore/cpprest/MultipartFormData.cpp index df86ee8d4544..94a5fb3164e4 100644 --- a/samples/client/petstore/cpprest/MultipartFormData.cpp +++ b/samples/client/petstore/cpprest/MultipartFormData.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/MultipartFormData.h b/samples/client/petstore/cpprest/MultipartFormData.h index 6a259f43cbcb..29896d3301c8 100644 --- a/samples/client/petstore/cpprest/MultipartFormData.h +++ b/samples/client/petstore/cpprest/MultipartFormData.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/Object.cpp b/samples/client/petstore/cpprest/Object.cpp index 985b229d8d19..80434226633e 100644 --- a/samples/client/petstore/cpprest/Object.cpp +++ b/samples/client/petstore/cpprest/Object.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/Object.h b/samples/client/petstore/cpprest/Object.h index 7b661929fb10..2bba167faff1 100644 --- a/samples/client/petstore/cpprest/Object.h +++ b/samples/client/petstore/cpprest/Object.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -16,8 +16,8 @@ * This is the implementation of a JSON object. */ -#ifndef _Object_H_ -#define _Object_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_Object_H_ +#define IO_SWAGGER_CLIENT_MODEL_Object_H_ #include "ModelBase.h" @@ -60,4 +60,4 @@ class Object : public ModelBase } } -#endif /* _Object_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_Object_H_ */ diff --git a/samples/client/petstore/cpprest/api/PetApi.cpp b/samples/client/petstore/cpprest/api/PetApi.cpp index 966907bb6807..27130805d89a 100644 --- a/samples/client/petstore/cpprest/api/PetApi.cpp +++ b/samples/client/petstore/cpprest/api/PetApi.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -36,13 +36,13 @@ PetApi::~PetApi() { } -pplx::task PetApi::addPet(std::shared_ptr body) +pplx::task PetApi::addPet(std::shared_ptr pet) { - // verify the required parameter 'body' is set - if (body == nullptr) + // verify the required parameter 'pet' is set + if (pet == nullptr) { - throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'body' when calling PetApi->addPet")); + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'pet' when calling PetApi->addPet")); } @@ -55,8 +55,6 @@ pplx::task PetApi::addPet(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; @@ -96,7 +94,8 @@ pplx::task PetApi::addPet(std::shared_ptr body) requestHttpContentType = utility::conversions::to_string_t("application/json"); web::json::value json; - json = ModelBase::toJson(body); + json = ModelBase::toJson(pet); + httpBody = std::shared_ptr( new JsonBody( json ) ); } @@ -105,9 +104,10 @@ pplx::task PetApi::addPet(std::shared_ptr body) { requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); - if(body.get()) + + if(pet.get()) { - body->toMultipart(multipart, utility::conversions::to_string_t("body")); + pet->toMultipart(multipart, utility::conversions::to_string_t("pet")); } httpBody = multipart; @@ -169,8 +169,6 @@ pplx::task PetApi::deletePet(int64_t petId, boost::optional> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; @@ -301,7 +299,7 @@ pplx::task>> PetApi::findPetsByStatus(std::vect std::unordered_set consumeHttpContentTypes; { - queryParams[utility::conversions::to_string_t("status")] = ApiClient::parameterToArrayString(status); + queryParams[utility::conversions::to_string_t("status")] = ApiClient::parameterToString(status); } std::shared_ptr httpBody; @@ -427,7 +425,7 @@ pplx::task>> PetApi::findPetsByTags(std::vector std::unordered_set consumeHttpContentTypes; { - queryParams[utility::conversions::to_string_t("tags")] = ApiClient::parameterToArrayString(tags); + queryParams[utility::conversions::to_string_t("tags")] = ApiClient::parameterToString(tags); } std::shared_ptr httpBody; @@ -633,13 +631,13 @@ pplx::task> PetApi::getPetById(int64_t petId) return result; }); } -pplx::task PetApi::updatePet(std::shared_ptr body) +pplx::task PetApi::updatePet(std::shared_ptr pet) { - // verify the required parameter 'body' is set - if (body == nullptr) + // verify the required parameter 'pet' is set + if (pet == nullptr) { - throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'body' when calling PetApi->updatePet")); + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'pet' when calling PetApi->updatePet")); } @@ -652,8 +650,6 @@ pplx::task PetApi::updatePet(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; @@ -693,7 +689,8 @@ pplx::task PetApi::updatePet(std::shared_ptr body) requestHttpContentType = utility::conversions::to_string_t("application/json"); web::json::value json; - json = ModelBase::toJson(body); + json = ModelBase::toJson(pet); + httpBody = std::shared_ptr( new JsonBody( json ) ); } @@ -702,9 +699,10 @@ pplx::task PetApi::updatePet(std::shared_ptr body) { requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); - if(body.get()) + + if(pet.get()) { - body->toMultipart(multipart, utility::conversions::to_string_t("body")); + pet->toMultipart(multipart, utility::conversions::to_string_t("pet")); } httpBody = multipart; @@ -766,8 +764,6 @@ pplx::task PetApi::updatePetWithForm(int64_t petId, boost::optional> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; @@ -860,7 +856,7 @@ pplx::task PetApi::updatePetWithForm(int64_t petId, boost::optional> PetApi::uploadFile(int64_t petId, boost::optional additionalMetadata, boost::optional> file) +pplx::task> PetApi::uploadFile(int64_t petId, boost::optional additionalMetadata, boost::optional file) { @@ -907,7 +903,7 @@ pplx::task> PetApi::uploadFile(int64_t petId, boost { formParams[ utility::conversions::to_string_t("additionalMetadata") ] = ApiClient::parameterToString(*additionalMetadata); } - if (file && *file != nullptr) + if (file) { fileParams[ utility::conversions::to_string_t("file") ] = *file; } diff --git a/samples/client/petstore/cpprest/api/PetApi.h b/samples/client/petstore/cpprest/api/PetApi.h index 99b335bca77e..44656672f494 100644 --- a/samples/client/petstore/cpprest/api/PetApi.h +++ b/samples/client/petstore/cpprest/api/PetApi.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -47,9 +47,9 @@ class PetApi /// /// /// - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store pplx::task addPet( - std::shared_ptr body + std::shared_ptr pet ); /// /// Deletes a pet @@ -99,9 +99,9 @@ class PetApi /// /// /// - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store pplx::task updatePet( - std::shared_ptr body + std::shared_ptr pet ); /// /// Updates a pet in the store with form data @@ -129,7 +129,7 @@ class PetApi pplx::task> uploadFile( int64_t petId, boost::optional additionalMetadata, - boost::optional> file + boost::optional file ); protected: diff --git a/samples/client/petstore/cpprest/api/StoreApi.cpp b/samples/client/petstore/cpprest/api/StoreApi.cpp index 03a10677b85d..6357690d2168 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.cpp +++ b/samples/client/petstore/cpprest/api/StoreApi.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -50,8 +50,6 @@ pplx::task StoreApi::deleteOrder(utility::string_t orderId) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; @@ -374,13 +372,13 @@ pplx::task> StoreApi::getOrderById(int64_t orderId) return result; }); } -pplx::task> StoreApi::placeOrder(std::shared_ptr body) +pplx::task> StoreApi::placeOrder(std::shared_ptr order) { - // verify the required parameter 'body' is set - if (body == nullptr) + // verify the required parameter 'order' is set + if (order == nullptr) { - throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'body' when calling StoreApi->placeOrder")); + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'order' when calling StoreApi->placeOrder")); } @@ -421,6 +419,7 @@ pplx::task> StoreApi::placeOrder(std::shared_ptr b headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; + consumeHttpContentTypes.insert( utility::conversions::to_string_t("*/*") ); std::shared_ptr httpBody; @@ -432,7 +431,8 @@ pplx::task> StoreApi::placeOrder(std::shared_ptr b requestHttpContentType = utility::conversions::to_string_t("application/json"); web::json::value json; - json = ModelBase::toJson(body); + json = ModelBase::toJson(order); + httpBody = std::shared_ptr( new JsonBody( json ) ); } @@ -441,9 +441,10 @@ pplx::task> StoreApi::placeOrder(std::shared_ptr b { requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); - if(body.get()) + + if(order.get()) { - body->toMultipart(multipart, utility::conversions::to_string_t("body")); + order->toMultipart(multipart, utility::conversions::to_string_t("order")); } httpBody = multipart; diff --git a/samples/client/petstore/cpprest/api/StoreApi.h b/samples/client/petstore/cpprest/api/StoreApi.h index 740d0673d62f..c9fd9202bd00 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.h +++ b/samples/client/petstore/cpprest/api/StoreApi.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -74,9 +74,9 @@ class StoreApi /// /// /// - /// order placed for purchasing the pet + /// order placed for purchasing the pet pplx::task> placeOrder( - std::shared_ptr body + std::shared_ptr order ); protected: diff --git a/samples/client/petstore/cpprest/api/UserApi.cpp b/samples/client/petstore/cpprest/api/UserApi.cpp index 681d2ad2a167..920131cfeb91 100644 --- a/samples/client/petstore/cpprest/api/UserApi.cpp +++ b/samples/client/petstore/cpprest/api/UserApi.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -36,13 +36,13 @@ UserApi::~UserApi() { } -pplx::task UserApi::createUser(std::shared_ptr body) +pplx::task UserApi::createUser(std::shared_ptr user) { - // verify the required parameter 'body' is set - if (body == nullptr) + // verify the required parameter 'user' is set + if (user == nullptr) { - throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'body' when calling UserApi->createUser")); + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'user' when calling UserApi->createUser")); } @@ -55,8 +55,6 @@ pplx::task UserApi::createUser(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; @@ -83,6 +81,7 @@ pplx::task UserApi::createUser(std::shared_ptr body) headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; + consumeHttpContentTypes.insert( utility::conversions::to_string_t("*/*") ); std::shared_ptr httpBody; @@ -94,7 +93,8 @@ pplx::task UserApi::createUser(std::shared_ptr body) requestHttpContentType = utility::conversions::to_string_t("application/json"); web::json::value json; - json = ModelBase::toJson(body); + json = ModelBase::toJson(user); + httpBody = std::shared_ptr( new JsonBody( json ) ); } @@ -103,9 +103,10 @@ pplx::task UserApi::createUser(std::shared_ptr body) { requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); - if(body.get()) + + if(user.get()) { - body->toMultipart(multipart, utility::conversions::to_string_t("body")); + user->toMultipart(multipart, utility::conversions::to_string_t("user")); } httpBody = multipart; @@ -151,7 +152,7 @@ pplx::task UserApi::createUser(std::shared_ptr body) return void(); }); } -pplx::task UserApi::createUsersWithArrayInput(std::vector> body) +pplx::task UserApi::createUsersWithArrayInput(std::vector> user) { @@ -164,8 +165,6 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; @@ -192,6 +191,7 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector consumeHttpContentTypes; + consumeHttpContentTypes.insert( utility::conversions::to_string_t("*/*") ); std::shared_ptr httpBody; @@ -205,14 +205,14 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector jsonArray; - for( auto& item : body ) + for( auto& item : user ) { jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() ); } json = web::json::value::array(jsonArray); } - + httpBody = std::shared_ptr( new JsonBody( json ) ); } // multipart formdata @@ -222,14 +222,14 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector multipart(new MultipartFormData); { std::vector jsonArray; - for( auto& item : body ) + for( auto& item : user ) { jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() ); } - multipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("body"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); + multipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("user"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); } - + httpBody = multipart; requestHttpContentType += utility::conversions::to_string_t("; boundary=") + multipart->getBoundary(); } @@ -273,7 +273,7 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector UserApi::createUsersWithListInput(std::vector> body) +pplx::task UserApi::createUsersWithListInput(std::vector> user) { @@ -286,8 +286,6 @@ pplx::task UserApi::createUsersWithListInput(std::vector> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; @@ -314,6 +312,7 @@ pplx::task UserApi::createUsersWithListInput(std::vector consumeHttpContentTypes; + consumeHttpContentTypes.insert( utility::conversions::to_string_t("*/*") ); std::shared_ptr httpBody; @@ -327,14 +326,14 @@ pplx::task UserApi::createUsersWithListInput(std::vector jsonArray; - for( auto& item : body ) + for( auto& item : user ) { jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() ); } json = web::json::value::array(jsonArray); } - + httpBody = std::shared_ptr( new JsonBody( json ) ); } // multipart formdata @@ -344,14 +343,14 @@ pplx::task UserApi::createUsersWithListInput(std::vector multipart(new MultipartFormData); { std::vector jsonArray; - for( auto& item : body ) + for( auto& item : user ) { jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() ); } - multipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("body"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); + multipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("user"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); } - + httpBody = multipart; requestHttpContentType += utility::conversions::to_string_t("; boundary=") + multipart->getBoundary(); } @@ -409,8 +408,6 @@ pplx::task UserApi::deleteUser(utility::string_t username) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; @@ -750,8 +747,6 @@ pplx::task UserApi::logoutUser() std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; @@ -833,13 +828,13 @@ pplx::task UserApi::logoutUser() return void(); }); } -pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr body) +pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr user) { - // verify the required parameter 'body' is set - if (body == nullptr) + // verify the required parameter 'user' is set + if (user == nullptr) { - throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'body' when calling UserApi->updateUser")); + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'user' when calling UserApi->updateUser")); } @@ -853,8 +848,6 @@ pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); - responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; @@ -881,6 +874,7 @@ pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; + consumeHttpContentTypes.insert( utility::conversions::to_string_t("*/*") ); std::shared_ptr httpBody; @@ -892,7 +886,8 @@ pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr requestHttpContentType = utility::conversions::to_string_t("application/json"); web::json::value json; - json = ModelBase::toJson(body); + json = ModelBase::toJson(user); + httpBody = std::shared_ptr( new JsonBody( json ) ); } @@ -901,9 +896,10 @@ pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr { requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); - if(body.get()) + + if(user.get()) { - body->toMultipart(multipart, utility::conversions::to_string_t("body")); + user->toMultipart(multipart, utility::conversions::to_string_t("user")); } httpBody = multipart; diff --git a/samples/client/petstore/cpprest/api/UserApi.h b/samples/client/petstore/cpprest/api/UserApi.h index 83d80dfedc99..aa86f728eca6 100644 --- a/samples/client/petstore/cpprest/api/UserApi.h +++ b/samples/client/petstore/cpprest/api/UserApi.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -23,7 +23,6 @@ #include "../ApiClient.h" #include "User.h" -#include #include #include @@ -46,9 +45,9 @@ class UserApi /// /// This can only be done by the logged in user. /// - /// Created user object + /// Created user object pplx::task createUser( - std::shared_ptr body + std::shared_ptr user ); /// /// Creates list of users with given input array @@ -56,9 +55,9 @@ class UserApi /// /// /// - /// List of user object + /// List of user object pplx::task createUsersWithArrayInput( - std::vector> body + std::vector> user ); /// /// Creates list of users with given input array @@ -66,9 +65,9 @@ class UserApi /// /// /// - /// List of user object + /// List of user object pplx::task createUsersWithListInput( - std::vector> body + std::vector> user ); /// /// Delete user @@ -86,7 +85,7 @@ class UserApi /// /// /// - /// The name that needs to be fetched. Use user1 for testing. + /// The name that needs to be fetched. Use user1 for testing. pplx::task> getUserByName( utility::string_t username ); @@ -117,10 +116,10 @@ class UserApi /// This can only be done by the logged in user. /// /// name that need to be deleted - /// Updated user object + /// Updated user object pplx::task updateUser( utility::string_t username, - std::shared_ptr body + std::shared_ptr user ); protected: diff --git a/samples/client/petstore/cpprest/git_push.sh b/samples/client/petstore/cpprest/git_push.sh index 35d20f1851db..bd57362e9cac 100644 --- a/samples/client/petstore/cpprest/git_push.sh +++ b/samples/client/petstore/cpprest/git_push.sh @@ -36,7 +36,7 @@ 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 crediential in your environment." + 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 diff --git a/samples/client/petstore/cpprest/model/ApiResponse.cpp b/samples/client/petstore/cpprest/model/ApiResponse.cpp index 7b51c7b94d5f..a0dd5de26729 100644 --- a/samples/client/petstore/cpprest/model/ApiResponse.cpp +++ b/samples/client/petstore/cpprest/model/ApiResponse.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/model/ApiResponse.h b/samples/client/petstore/cpprest/model/ApiResponse.h index 5b78aa749adf..cac05161df7d 100644 --- a/samples/client/petstore/cpprest/model/ApiResponse.h +++ b/samples/client/petstore/cpprest/model/ApiResponse.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/model/Category.cpp b/samples/client/petstore/cpprest/model/Category.cpp index 4362719cb9c3..e1fe35f5e660 100644 --- a/samples/client/petstore/cpprest/model/Category.cpp +++ b/samples/client/petstore/cpprest/model/Category.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/model/Category.h b/samples/client/petstore/cpprest/model/Category.h index eac7f30e7181..b6ba0b6c3daa 100644 --- a/samples/client/petstore/cpprest/model/Category.h +++ b/samples/client/petstore/cpprest/model/Category.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/model/Order.cpp b/samples/client/petstore/cpprest/model/Order.cpp index 60b30a9a46da..5276e43c3145 100644 --- a/samples/client/petstore/cpprest/model/Order.cpp +++ b/samples/client/petstore/cpprest/model/Order.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/model/Order.h b/samples/client/petstore/cpprest/model/Order.h index d43f15994f0e..bc62a7b465b0 100644 --- a/samples/client/petstore/cpprest/model/Order.h +++ b/samples/client/petstore/cpprest/model/Order.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/model/Pet.cpp b/samples/client/petstore/cpprest/model/Pet.cpp index f2e23fb8ea7a..580787516efe 100644 --- a/samples/client/petstore/cpprest/model/Pet.cpp +++ b/samples/client/petstore/cpprest/model/Pet.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/model/Pet.h b/samples/client/petstore/cpprest/model/Pet.h index fd5b40407015..89dea97787fd 100644 --- a/samples/client/petstore/cpprest/model/Pet.h +++ b/samples/client/petstore/cpprest/model/Pet.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/model/Tag.cpp b/samples/client/petstore/cpprest/model/Tag.cpp index 2594f8553d31..00850d62c35e 100644 --- a/samples/client/petstore/cpprest/model/Tag.cpp +++ b/samples/client/petstore/cpprest/model/Tag.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/model/Tag.h b/samples/client/petstore/cpprest/model/Tag.h index 27cc5958cf45..143b329932d3 100644 --- a/samples/client/petstore/cpprest/model/Tag.h +++ b/samples/client/petstore/cpprest/model/Tag.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/model/User.cpp b/samples/client/petstore/cpprest/model/User.cpp index 53fe5e3fd874..ed8402b555bf 100644 --- a/samples/client/petstore/cpprest/model/User.cpp +++ b/samples/client/petstore/cpprest/model/User.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpprest/model/User.h b/samples/client/petstore/cpprest/model/User.h index d2272b03a20b..3c0280353ad6 100644 --- a/samples/client/petstore/cpprest/model/User.h +++ b/samples/client/petstore/cpprest/model/User.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/client/petstore/eiffel/test/apis/pet_api_test.e b/samples/client/petstore/eiffel/test/apis/pet_api_test.e index d7e12953695f..0cccf1eb8b62 100644 --- a/samples/client/petstore/eiffel/test/apis/pet_api_test.e +++ b/samples/client/petstore/eiffel/test/apis/pet_api_test.e @@ -60,7 +60,7 @@ feature -- Test routines test_find_pets_by_tags -- Finds Pets by tags -- - -- Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + -- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. local l_response: LIST [PET] l_tags: LIST [STRING_32] diff --git a/samples/client/petstore/flash/.swagger-codegen/VERSION b/samples/client/petstore/flash/.swagger-codegen/VERSION index 7fea99011a6f..096bf47efe31 100644 --- a/samples/client/petstore/flash/.swagger-codegen/VERSION +++ b/samples/client/petstore/flash/.swagger-codegen/VERSION @@ -1 +1 @@ -2.2.3-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/flash/flash/build.xml b/samples/client/petstore/flash/flash/build.xml index 9b84a466b766..5f4922470c0a 100644 --- a/samples/client/petstore/flash/flash/build.xml +++ b/samples/client/petstore/flash/flash/build.xml @@ -63,7 +63,7 @@ - + diff --git a/samples/client/petstore/flash/flash/src/io/swagger/client/api/PetApi.as b/samples/client/petstore/flash/flash/src/io/swagger/client/api/PetApi.as index 55c861c7e59a..2479900173e0 100644 --- a/samples/client/petstore/flash/flash/src/io/swagger/client/api/PetApi.as +++ b/samples/client/petstore/flash/flash/src/io/swagger/client/api/PetApi.as @@ -38,7 +38,7 @@ public class PetApi extends SwaggerApi { /* * Returns void */ - public function add_pet (body: Pet): String { + public function add_pet (pet: Pet): String { // create path and map variables var path: String = "/pet".replace(/{format}/g,"xml"); @@ -53,7 +53,7 @@ public class PetApi extends SwaggerApi { - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, pet, headerParams); var requestId: String = getUniqueId(); @@ -197,7 +197,7 @@ public class PetApi extends SwaggerApi { /* * Returns void */ - public function update_pet (body: Pet): String { + public function update_pet (pet: Pet): String { // create path and map variables var path: String = "/pet".replace(/{format}/g,"xml"); @@ -212,7 +212,7 @@ public class PetApi extends SwaggerApi { - var token:AsyncToken = getApiInvoker().invokeAPI(path, "PUT", queryParams, body, headerParams); + var token:AsyncToken = getApiInvoker().invokeAPI(path, "PUT", queryParams, pet, headerParams); var requestId: String = getUniqueId(); diff --git a/samples/client/petstore/flash/flash/src/io/swagger/client/api/StoreApi.as b/samples/client/petstore/flash/flash/src/io/swagger/client/api/StoreApi.as index d4f7fc43d9fa..c8a3dd55f021 100644 --- a/samples/client/petstore/flash/flash/src/io/swagger/client/api/StoreApi.as +++ b/samples/client/petstore/flash/flash/src/io/swagger/client/api/StoreApi.as @@ -118,7 +118,7 @@ public class StoreApi extends SwaggerApi { /* * Returns Order */ - public function place_order (body: Order): String { + public function place_order (order: Order): String { // create path and map variables var path: String = "/store/order".replace(/{format}/g,"xml"); @@ -133,7 +133,7 @@ public class StoreApi extends SwaggerApi { - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, order, headerParams); var requestId: String = getUniqueId(); diff --git a/samples/client/petstore/flash/flash/src/io/swagger/client/api/UserApi.as b/samples/client/petstore/flash/flash/src/io/swagger/client/api/UserApi.as index bdb910694610..1949c01468f0 100644 --- a/samples/client/petstore/flash/flash/src/io/swagger/client/api/UserApi.as +++ b/samples/client/petstore/flash/flash/src/io/swagger/client/api/UserApi.as @@ -36,7 +36,7 @@ public class UserApi extends SwaggerApi { /* * Returns void */ - public function create_user (body: User): String { + public function create_user (user: User): String { // create path and map variables var path: String = "/user".replace(/{format}/g,"xml"); @@ -51,7 +51,7 @@ public class UserApi extends SwaggerApi { - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, user, headerParams); var requestId: String = getUniqueId(); @@ -66,7 +66,7 @@ public class UserApi extends SwaggerApi { /* * Returns void */ - public function create_users_with_array_input (body: Array): String { + public function create_users_with_array_input (user: Array): String { // create path and map variables var path: String = "/user/createWithArray".replace(/{format}/g,"xml"); @@ -81,7 +81,7 @@ public class UserApi extends SwaggerApi { - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, user, headerParams); var requestId: String = getUniqueId(); @@ -96,7 +96,7 @@ public class UserApi extends SwaggerApi { /* * Returns void */ - public function create_users_with_list_input (body: Array): String { + public function create_users_with_list_input (user: Array): String { // create path and map variables var path: String = "/user/createWithList".replace(/{format}/g,"xml"); @@ -111,7 +111,7 @@ public class UserApi extends SwaggerApi { - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, user, headerParams); var requestId: String = getUniqueId(); @@ -250,7 +250,7 @@ if("null" != String(password)) /* * Returns void */ - public function update_user (username: String, body: User): String { + public function update_user (username: String, user: User): String { // create path and map variables var path: String = "/user/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); @@ -269,7 +269,7 @@ if("null" != String(password)) - var token:AsyncToken = getApiInvoker().invokeAPI(path, "PUT", queryParams, body, headerParams); + var token:AsyncToken = getApiInvoker().invokeAPI(path, "PUT", queryParams, user, headerParams); var requestId: String = getUniqueId(); diff --git a/samples/client/petstore/flash/git_push.sh b/samples/client/petstore/flash/git_push.sh index ed374619b139..ae01b182ae9e 100644 --- a/samples/client/petstore/flash/git_push.sh +++ b/samples/client/petstore/flash/git_push.sh @@ -36,7 +36,7 @@ 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 crediential in your environment." + 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 diff --git a/samples/client/petstore/java/feign/.swagger-codegen/VERSION b/samples/client/petstore/java/feign/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/feign/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/feign/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/google-api-client/.swagger-codegen/VERSION b/samples/client/petstore/java/google-api-client/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/google-api-client/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/google-api-client/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/jersey1/.swagger-codegen/VERSION b/samples/client/petstore/java/jersey1/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/jersey1/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/jersey1/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java6/.swagger-codegen/VERSION b/samples/client/petstore/java/jersey2-java6/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/jersey2-java6/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/jersey2-java6/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8/.swagger-codegen/VERSION b/samples/client/petstore/java/jersey2-java8/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/jersey2-java8/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/jersey2-java8/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/.swagger-codegen/VERSION b/samples/client/petstore/java/jersey2/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/jersey2/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/jersey2/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/.swagger-codegen/VERSION b/samples/client/petstore/java/okhttp-gson-parcelableModel/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/README.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/README.md index 8e55bbc51a23..cb9aa7a4531b 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/README.md +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/README.md @@ -1,24 +1,35 @@ # swagger-petstore-okhttp-gson +Swagger Petstore +- API version: 1.0.0 + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + +*Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen)* + + ## Requirements -Building the API client library requires [Maven](https://maven.apache.org/) to be installed. +Building the API client library requires: +1. Java 1.7+ +2. Maven/Gradle ## Installation To install the API client library to your local Maven repository, simply execute: ```shell -mvn install +mvn clean install ``` To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: ```shell -mvn deploy +mvn clean deploy ``` -Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. ### Maven users @@ -26,10 +37,10 @@ Add this dependency to your project's POM: ```xml - io.swagger - swagger-petstore-okhttp-gson - 1.0.0 - compile + io.swagger + swagger-petstore-okhttp-gson + 1.0.0 + compile ``` @@ -45,12 +56,14 @@ compile "io.swagger:swagger-petstore-okhttp-gson:1.0.0" At first generate the JAR by executing: - mvn package +```shell +mvn clean package +``` Then manually install the following JARs: -* target/swagger-petstore-okhttp-gson-1.0.0.jar -* target/lib/*.jar +* `target/swagger-petstore-okhttp-gson-1.0.0.jar` +* `target/lib/*.jar` ## Getting Started @@ -61,22 +74,22 @@ Please follow the [installation](#installation) instruction and execute the foll import io.swagger.client.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; -import io.swagger.client.api.FakeApi; +import io.swagger.client.api.AnotherFakeApi; import java.io.File; import java.util.*; -public class FakeApiExample { +public class AnotherFakeApiExample { public static void main(String[] args) { - FakeApi apiInstance = new FakeApi(); - Boolean body = true; // Boolean | Input boolean as post body + AnotherFakeApi apiInstance = new AnotherFakeApi(); + Client body = new Client(); // Client | client model try { - Boolean result = apiInstance.fakeOuterBooleanSerialize(body); + Client result = apiInstance.testSpecialTags(body); System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeOuterBooleanSerialize"); + System.err.println("Exception when calling AnotherFakeApi#testSpecialTags"); e.printStackTrace(); } } @@ -90,6 +103,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**testSpecialTags**](docs/AnotherFakeApi.md#testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags *FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | *FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | @@ -97,6 +111,9 @@ Class | Method | HTTP request | Description *FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case *PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store *PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status @@ -164,6 +181,12 @@ Authentication schemes defined for the API: - **API key parameter name**: api_key - **Location**: HTTP header +### api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + ### http_basic_test - **Type**: HTTP basic authentication diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md index 08fee3448821..ca048bcc515b 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumStringRequired** | [**EnumStringRequiredEnum**](#EnumStringRequiredEnum) | | **enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] **enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] **outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] @@ -19,6 +20,15 @@ LOWER | "lower" EMPTY | "" + +## Enum: EnumStringRequiredEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" +EMPTY | "" + + ## Enum: EnumIntegerEnum Name | Value diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index d6232b0766d6..7ce8204c39f9 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -40,6 +40,8 @@ public class AdditionalPropertiesClass implements Parcelable { @SerializedName("map_of_map_property") private Map> mapOfMapProperty = null; + public AdditionalPropertiesClass() { + } public AdditionalPropertiesClass mapProperty(Map mapProperty) { this.mapProperty = mapProperty; return this; @@ -134,19 +136,13 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(mapProperty); - out.writeValue(mapOfMapProperty); } - public AdditionalPropertiesClass() { - super(); - } - AdditionalPropertiesClass(Parcel in) { - mapProperty = (Map)in.readValue(null); mapOfMapProperty = (Map>)in.readValue(Map.class.getClassLoader()); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java index 07b8f0ec8d74..464660e8ab4d 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java @@ -119,19 +119,13 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(className); - out.writeValue(color); } - public Animal() { - super(); - } - Animal(Parcel in) { - className = (String)in.readValue(null); color = (String)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AnimalFarm.java index e8f3fe5a5352..636fd5f15fa6 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -26,6 +26,9 @@ */ public class AnimalFarm extends ArrayList implements Parcelable { + public AnimalFarm() { + super(); + } @Override public boolean equals(java.lang.Object o) { @@ -64,15 +67,13 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } - public void writeToParcel(Parcel out, int flags) { - super.writeToParcel(out, flags); } - public AnimalFarm() { - super(); + public void writeToParcel(Parcel out, int flags) { + out.writeList(this); } AnimalFarm(Parcel in) { - super(in); + in.readTypedList(this, Animal.CREATOR); } public int describeContents() { @@ -81,7 +82,9 @@ public int describeContents() { public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public AnimalFarm createFromParcel(Parcel in) { - return new AnimalFarm(in); + AnimalFarm result = new AnimalFarm(); + result.addAll(in.readArrayList(Animal.class.getClassLoader())); + return result; } public AnimalFarm[] newArray(int size) { return new AnimalFarm[size]; diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 8e1541bb0211..1faee2b42783 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -37,6 +37,8 @@ public class ArrayOfArrayOfNumberOnly implements Parcelable { @SerializedName("ArrayArrayNumber") private List> arrayArrayNumber = null; + public ArrayOfArrayOfNumberOnly() { + } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { this.arrayArrayNumber = arrayArrayNumber; return this; @@ -103,17 +105,12 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(arrayArrayNumber); } - public ArrayOfArrayOfNumberOnly() { - super(); - } - ArrayOfArrayOfNumberOnly(Parcel in) { - arrayArrayNumber = (List>)in.readValue(List.class.getClassLoader()); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 8f81852c594c..700c0804ca19 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -37,6 +37,8 @@ public class ArrayOfNumberOnly implements Parcelable { @SerializedName("ArrayNumber") private List arrayNumber = null; + public ArrayOfNumberOnly() { + } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { this.arrayNumber = arrayNumber; return this; @@ -103,17 +105,12 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(arrayNumber); } - public ArrayOfNumberOnly() { - super(); - } - ArrayOfNumberOnly(Parcel in) { - arrayNumber = (List)in.readValue(BigDecimal.class.getClassLoader()); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayTest.java index 5e1826abb582..81ff78192d51 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayTest.java @@ -43,6 +43,8 @@ public class ArrayTest implements Parcelable { @SerializedName("array_array_of_model") private List> arrayArrayOfModel = null; + public ArrayTest() { + } public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; @@ -165,21 +167,14 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(arrayOfString); - out.writeValue(arrayArrayOfInteger); - out.writeValue(arrayArrayOfModel); } - public ArrayTest() { - super(); - } - ArrayTest(Parcel in) { - arrayOfString = (List)in.readValue(null); arrayArrayOfInteger = (List>)in.readValue(List.class.getClassLoader()); arrayArrayOfModel = (List>)in.readValue(List.class.getClassLoader()); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Capitalization.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Capitalization.java index 57bef2e24bf4..bbe57c622f33 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Capitalization.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Capitalization.java @@ -49,6 +49,8 @@ public class Capitalization implements Parcelable { @SerializedName("ATT_NAME") private String ATT_NAME = null; + public Capitalization() { + } public Capitalization smallCamel(String smallCamel) { this.smallCamel = smallCamel; return this; @@ -207,27 +209,17 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(smallCamel); - out.writeValue(capitalCamel); - out.writeValue(smallSnake); - out.writeValue(capitalSnake); - out.writeValue(scAETHFlowPoints); - out.writeValue(ATT_NAME); } - public Capitalization() { - super(); - } - Capitalization(Parcel in) { - smallCamel = (String)in.readValue(null); capitalCamel = (String)in.readValue(null); smallSnake = (String)in.readValue(null); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.java index ad00926df65a..575377073f3e 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.java @@ -35,6 +35,9 @@ public class Cat extends Animal implements Parcelable { @SerializedName("declawed") private Boolean declawed = null; + public Cat() { + super(); + } public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; @@ -94,17 +97,14 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - super.writeToParcel(out, flags); + super.writeToParcel(out, flags); out.writeValue(declawed); } - public Cat() { - super(); - } - Cat(Parcel in) { - super(in); + super(in); declawed = (Boolean)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Category.java index 6d5eec8a0960..8fc091f1ab8a 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Category.java @@ -37,6 +37,8 @@ public class Category implements Parcelable { @SerializedName("name") private String name = null; + public Category() { + } public Category id(Long id) { this.id = id; return this; @@ -115,19 +117,13 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(id); - out.writeValue(name); } - public Category() { - super(); - } - Category(Parcel in) { - id = (Long)in.readValue(null); name = (String)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ClassModel.java index 6740f0f8ae4a..30338298321f 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ClassModel.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ClassModel.java @@ -35,6 +35,8 @@ public class ClassModel implements Parcelable { @SerializedName("_class") private String propertyClass = null; + public ClassModel() { + } public ClassModel propertyClass(String propertyClass) { this.propertyClass = propertyClass; return this; @@ -93,17 +95,12 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(propertyClass); } - public ClassModel() { - super(); - } - ClassModel(Parcel in) { - propertyClass = (String)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Client.java index 51e327d3e94d..8803507238f8 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Client.java @@ -34,6 +34,8 @@ public class Client implements Parcelable { @SerializedName("client") private String client = null; + public Client() { + } public Client client(String client) { this.client = client; return this; @@ -92,17 +94,12 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(client); } - public Client() { - super(); - } - Client(Parcel in) { - client = (String)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.java index a25dc15265a3..68f4b76980d5 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.java @@ -35,6 +35,9 @@ public class Dog extends Animal implements Parcelable { @SerializedName("breed") private String breed = null; + public Dog() { + super(); + } public Dog breed(String breed) { this.breed = breed; return this; @@ -94,17 +97,14 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - super.writeToParcel(out, flags); + super.writeToParcel(out, flags); out.writeValue(breed); } - public Dog() { - super(); - } - Dog(Parcel in) { - super(in); + super(in); breed = (String)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumArrays.java index 4483b1066ee7..8bccde759a12 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumArrays.java @@ -133,6 +133,8 @@ public ArrayEnumEnum read(final JsonReader jsonReader) throws IOException { @SerializedName("array_enum") private List arrayEnum = null; + public EnumArrays() { + } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { this.justSymbol = justSymbol; return this; @@ -219,19 +221,13 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(justSymbol); - out.writeValue(arrayEnum); } - public EnumArrays() { - super(); - } - EnumArrays(Parcel in) { - justSymbol = (JustSymbolEnum)in.readValue(null); arrayEnum = (List)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java index 3d70e61b69c4..4f102f4f1e4f 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java @@ -84,6 +84,58 @@ public EnumStringEnum read(final JsonReader jsonReader) throws IOException { @SerializedName("enum_string") private EnumStringEnum enumString = null; + /** + * Gets or Sets enumStringRequired + */ + @JsonAdapter(EnumStringRequiredEnum.Adapter.class) + public enum EnumStringRequiredEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringRequiredEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStringRequiredEnum fromValue(String text) { + for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumStringRequiredEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumStringRequiredEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return EnumStringRequiredEnum.fromValue(String.valueOf(value)); + } + } + } + + @SerializedName("enum_string_required") + private EnumStringRequiredEnum enumStringRequired = null; + /** * Gets or Sets enumInteger */ @@ -187,6 +239,8 @@ public EnumNumberEnum read(final JsonReader jsonReader) throws IOException { @SerializedName("outerEnum") private OuterEnum outerEnum = null; + public EnumTest() { + } public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -205,6 +259,24 @@ public void setEnumString(EnumStringEnum enumString) { this.enumString = enumString; } + public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + return this; + } + + /** + * Get enumStringRequired + * @return enumStringRequired + **/ + @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; @@ -270,6 +342,7 @@ public boolean equals(java.lang.Object o) { } 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); @@ -277,7 +350,7 @@ public boolean equals(java.lang.Object o) { @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); + return Objects.hash(enumString, enumStringRequired, enumInteger, enumNumber, outerEnum); } @@ -287,6 +360,7 @@ public String toString() { 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"); @@ -305,24 +379,18 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(enumString); - + out.writeValue(enumStringRequired); out.writeValue(enumInteger); - out.writeValue(enumNumber); - out.writeValue(outerEnum); } - public EnumTest() { - super(); - } - EnumTest(Parcel in) { - enumString = (EnumStringEnum)in.readValue(null); + enumStringRequired = (EnumStringRequiredEnum)in.readValue(null); enumInteger = (EnumIntegerEnum)in.readValue(null); enumNumber = (EnumNumberEnum)in.readValue(null); outerEnum = (OuterEnum)in.readValue(OuterEnum.class.getClassLoader()); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/FormatTest.java index fa648da36940..4363f4015fd6 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/FormatTest.java @@ -74,6 +74,8 @@ public class FormatTest implements Parcelable { @SerializedName("password") private String password = null; + public FormatTest() { + } public FormatTest integer(Integer integer) { this.integer = integer; return this; @@ -382,41 +384,24 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(integer); - out.writeValue(int32); - out.writeValue(int64); - out.writeValue(number); - out.writeValue(_float); - out.writeValue(_double); - out.writeValue(string); - out.writeValue(_byte); - out.writeValue(binary); - out.writeValue(date); - out.writeValue(dateTime); - out.writeValue(uuid); - out.writeValue(password); } - public FormatTest() { - super(); - } - FormatTest(Parcel in) { - integer = (Integer)in.readValue(null); int32 = (Integer)in.readValue(null); int64 = (Long)in.readValue(null); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index e1c681dff37a..1f42bfddf3fc 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -37,6 +37,8 @@ public class HasOnlyReadOnly implements Parcelable { @SerializedName("foo") private String foo = null; + public HasOnlyReadOnly() { + } /** * Get bar * @return bar @@ -97,19 +99,13 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(bar); - out.writeValue(foo); } - public HasOnlyReadOnly() { - super(); - } - HasOnlyReadOnly(Parcel in) { - bar = (String)in.readValue(null); foo = (String)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MapTest.java index 0088eb96eeeb..97be941cffa4 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MapTest.java @@ -87,6 +87,8 @@ public InnerEnum read(final JsonReader jsonReader) throws IOException { @SerializedName("map_of_enum_string") private Map mapOfEnumString = null; + public MapTest() { + } public MapTest mapMapOfString(Map> mapMapOfString) { this.mapMapOfString = mapMapOfString; return this; @@ -181,19 +183,13 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(mapMapOfString); - out.writeValue(mapOfEnumString); } - public MapTest() { - super(); - } - MapTest(Parcel in) { - mapMapOfString = (Map>)in.readValue(Map.class.getClassLoader()); mapOfEnumString = (Map)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 2ff2d8f2a3e6..3e401f9ae2d3 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -46,6 +46,8 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Parcelable { @SerializedName("map") private Map map = null; + public MixedPropertiesAndAdditionalPropertiesClass() { + } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { this.uuid = uuid; return this; @@ -152,21 +154,14 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(uuid); - out.writeValue(dateTime); - out.writeValue(map); } - public MixedPropertiesAndAdditionalPropertiesClass() { - super(); - } - MixedPropertiesAndAdditionalPropertiesClass(Parcel in) { - uuid = (UUID)in.readValue(UUID.class.getClassLoader()); dateTime = (OffsetDateTime)in.readValue(OffsetDateTime.class.getClassLoader()); map = (Map)in.readValue(Animal.class.getClassLoader()); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Model200Response.java index d975c9e4b6a6..4ea40d8f1f25 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Model200Response.java @@ -38,6 +38,8 @@ public class Model200Response implements Parcelable { @SerializedName("class") private String propertyClass = null; + public Model200Response() { + } public Model200Response name(Integer name) { this.name = name; return this; @@ -116,19 +118,13 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(name); - out.writeValue(propertyClass); } - public Model200Response() { - super(); - } - Model200Response(Parcel in) { - name = (Integer)in.readValue(null); propertyClass = (String)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelApiResponse.java index 6b6d98de85e1..c37d9d6d5218 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -40,6 +40,8 @@ public class ModelApiResponse implements Parcelable { @SerializedName("message") private String message = null; + public ModelApiResponse() { + } public ModelApiResponse code(Integer code) { this.code = code; return this; @@ -138,21 +140,14 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(code); - out.writeValue(type); - out.writeValue(message); } - public ModelApiResponse() { - super(); - } - ModelApiResponse(Parcel in) { - code = (Integer)in.readValue(null); type = (String)in.readValue(null); message = (String)in.readValue(null); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelReturn.java index 6939dc5ee3dd..dd8b0ae4eb6e 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelReturn.java @@ -35,6 +35,8 @@ public class ModelReturn implements Parcelable { @SerializedName("return") private Integer _return = null; + public ModelReturn() { + } public ModelReturn _return(Integer _return) { this._return = _return; return this; @@ -93,17 +95,12 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(_return); } - public ModelReturn() { - super(); - } - ModelReturn(Parcel in) { - _return = (Integer)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Name.java index 13640af182b1..7c79b8abda45 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Name.java @@ -44,6 +44,8 @@ public class Name implements Parcelable { @SerializedName("123Number") private Integer _123Number = null; + public Name() { + } public Name name(Integer name) { this.name = name; return this; @@ -144,23 +146,15 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(name); - out.writeValue(snakeCase); - out.writeValue(property); - out.writeValue(_123Number); } - public Name() { - super(); - } - Name(Parcel in) { - name = (Integer)in.readValue(null); snakeCase = (Integer)in.readValue(null); property = (String)in.readValue(null); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/NumberOnly.java index be6d26ebfc6d..b646df644cfb 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/NumberOnly.java @@ -35,6 +35,8 @@ public class NumberOnly implements Parcelable { @SerializedName("JustNumber") private BigDecimal justNumber = null; + public NumberOnly() { + } public NumberOnly justNumber(BigDecimal justNumber) { this.justNumber = justNumber; return this; @@ -93,17 +95,12 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(justNumber); } - public NumberOnly() { - super(); - } - NumberOnly(Parcel in) { - justNumber = (BigDecimal)in.readValue(BigDecimal.class.getClassLoader()); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Order.java index 5d7e4dcd342a..afe88ba943e0 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Order.java @@ -99,6 +99,8 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { @SerializedName("complete") private Boolean complete = false; + public Order() { + } public Order id(Long id) { this.id = id; return this; @@ -257,27 +259,17 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(id); - out.writeValue(petId); - out.writeValue(quantity); - out.writeValue(shipDate); - out.writeValue(status); - out.writeValue(complete); } - public Order() { - super(); - } - Order(Parcel in) { - id = (Long)in.readValue(null); petId = (Long)in.readValue(null); quantity = (Integer)in.readValue(null); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/OuterComposite.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/OuterComposite.java index 323c7df04862..c5f5c06a3bbf 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/OuterComposite.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/OuterComposite.java @@ -41,6 +41,8 @@ public class OuterComposite implements Parcelable { @SerializedName("my_boolean") private Boolean myBoolean = null; + public OuterComposite() { + } public OuterComposite myNumber(BigDecimal myNumber) { this.myNumber = myNumber; return this; @@ -139,21 +141,14 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(myNumber); - out.writeValue(myString); - out.writeValue(myBoolean); } - public OuterComposite() { - super(); - } - OuterComposite(Parcel in) { - myNumber = (BigDecimal)in.readValue(BigDecimal.class.getClassLoader()); myString = (String)in.readValue(null); myBoolean = (Boolean)in.readValue(null); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Pet.java index 0e9fa7ee9a74..e4d4fdb4f7fc 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Pet.java @@ -102,6 +102,8 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { @SerializedName("status") private StatusEnum status = null; + public Pet() { + } public Pet id(Long id) { this.id = id; return this; @@ -273,27 +275,17 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(id); - out.writeValue(category); - out.writeValue(name); - out.writeValue(photoUrls); - out.writeValue(tags); - out.writeValue(status); } - public Pet() { - super(); - } - Pet(Parcel in) { - id = (Long)in.readValue(null); category = (Category)in.readValue(Category.class.getClassLoader()); name = (String)in.readValue(null); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index ddea1d71395e..d686c8055895 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -37,6 +37,8 @@ public class ReadOnlyFirst implements Parcelable { @SerializedName("baz") private String baz = null; + public ReadOnlyFirst() { + } /** * Get bar * @return bar @@ -106,19 +108,13 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(bar); - out.writeValue(baz); } - public ReadOnlyFirst() { - super(); - } - ReadOnlyFirst(Parcel in) { - bar = (String)in.readValue(null); baz = (String)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/SpecialModelName.java index d72d0735926a..ea63befdee26 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -34,6 +34,8 @@ public class SpecialModelName implements Parcelable { @SerializedName("$special[property.name]") private Long specialPropertyName = null; + public SpecialModelName() { + } public SpecialModelName specialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; return this; @@ -92,17 +94,12 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(specialPropertyName); } - public SpecialModelName() { - super(); - } - SpecialModelName(Parcel in) { - specialPropertyName = (Long)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Tag.java index 8fa924b834c5..e44ca7fb1848 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Tag.java @@ -37,6 +37,8 @@ public class Tag implements Parcelable { @SerializedName("name") private String name = null; + public Tag() { + } public Tag id(Long id) { this.id = id; return this; @@ -115,19 +117,13 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(id); - out.writeValue(name); } - public Tag() { - super(); - } - Tag(Parcel in) { - id = (Long)in.readValue(null); name = (String)in.readValue(null); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/User.java index 9de1dd0bc37d..894536904ea1 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/User.java @@ -55,6 +55,8 @@ public class User implements Parcelable { @SerializedName("userStatus") private Integer userStatus = null; + public User() { + } public User id(Long id) { this.id = id; return this; @@ -253,31 +255,19 @@ private String toIndentedString(java.lang.Object o) { return o.toString().replace("\n", "\n "); } + public void writeToParcel(Parcel out, int flags) { - out.writeValue(id); - out.writeValue(username); - out.writeValue(firstName); - out.writeValue(lastName); - out.writeValue(email); - out.writeValue(password); - out.writeValue(phone); - out.writeValue(userStatus); } - public User() { - super(); - } - User(Parcel in) { - id = (Long)in.readValue(null); username = (String)in.readValue(null); firstName = (String)in.readValue(null); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeApiTest.java index 169209bd418d..0e4979b29060 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeApiTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -16,8 +16,8 @@ import io.swagger.client.ApiException; import java.math.BigDecimal; import io.swagger.client.model.Client; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; import io.swagger.client.model.OuterComposite; import org.junit.Test; import org.junit.Ignore; @@ -137,7 +137,7 @@ public void testEndpointParametersTest() throws ApiException { String string = null; byte[] binary = null; LocalDate date = null; - DateTime dateTime = 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); @@ -168,4 +168,37 @@ public void testEnumParametersTest() throws ApiException { // TODO: test validations } + /** + * test inline additionalProperties + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testInlineAdditionalPropertiesTest() throws ApiException { + Object param = null; + api.testInlineAdditionalProperties(param); + + // TODO: test validations + } + + /** + * test json serialization of form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testJsonFormDataTest() throws ApiException { + String param = null; + String param2 = null; + api.testJsonFormData(param, param2); + + // TODO: test validations + } + } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeClassnameTags123ApiTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeClassnameTags123ApiTest.java index af5885aadddb..06147652aad6 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeClassnameTags123ApiTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeClassnameTags123ApiTest.java @@ -35,7 +35,7 @@ public class FakeClassnameTags123ApiTest { /** * To test class name in snake case * - * + * To test class name in snake case * * @throws ApiException * if the Api call fails diff --git a/samples/client/petstore/java/okhttp-gson/.swagger-codegen/VERSION b/samples/client/petstore/java/okhttp-gson/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/okhttp-gson/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/okhttp-gson/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/rest-assured/.swagger-codegen/VERSION b/samples/client/petstore/java/rest-assured/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/rest-assured/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/rest-assured/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resteasy/.swagger-codegen/VERSION b/samples/client/petstore/java/resteasy/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/resteasy/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/resteasy/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resteasy/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/resteasy/src/test/java/io/swagger/client/api/PetApiTest.java index ced6e945d991..8a39ab3b78b0 100644 --- a/samples/client/petstore/java/resteasy/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/resteasy/src/test/java/io/swagger/client/api/PetApiTest.java @@ -84,7 +84,7 @@ public void findPetsByStatusTest() throws ApiException { /** * Finds Pets by tags * - * Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * * @throws ApiException * if the Api call fails diff --git a/samples/client/petstore/java/resttemplate-withXml/.swagger-codegen/VERSION b/samples/client/petstore/java/resttemplate-withXml/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/resttemplate-withXml/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/resttemplate-withXml/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate/.swagger-codegen/VERSION b/samples/client/petstore/java/resttemplate/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/resttemplate/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/resttemplate/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/.swagger-codegen/VERSION b/samples/client/petstore/java/retrofit/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/retrofit/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/retrofit/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2-play24/.swagger-codegen/VERSION b/samples/client/petstore/java/retrofit2-play24/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/retrofit2-play24/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/retrofit2-play24/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/.swagger-codegen/VERSION b/samples/client/petstore/java/retrofit2/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/retrofit2/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/retrofit2/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/.swagger-codegen/VERSION b/samples/client/petstore/java/retrofit2rx/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/retrofit2rx/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/retrofit2rx/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx2/.swagger-codegen/VERSION b/samples/client/petstore/java/retrofit2rx2/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/java/retrofit2rx2/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/retrofit2rx2/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/jaxrs-cxf-client/.swagger-codegen-ignore b/samples/client/petstore/jaxrs-cxf-client/.swagger-codegen-ignore index 70b88e710391..c5fa491b4c55 100644 --- a/samples/client/petstore/jaxrs-cxf-client/.swagger-codegen-ignore +++ b/samples/client/petstore/jaxrs-cxf-client/.swagger-codegen-ignore @@ -21,5 +21,3 @@ #docs/*.md # Then explicitly reverse the ignore rule for a single file: #!docs/README.md - -**/impl/* \ No newline at end of file diff --git a/samples/client/petstore/jaxrs-cxf-client/.swagger-codegen/VERSION b/samples/client/petstore/jaxrs-cxf-client/.swagger-codegen/VERSION index 50794f17f1a5..855ff9501eb8 100644 --- a/samples/client/petstore/jaxrs-cxf-client/.swagger-codegen/VERSION +++ b/samples/client/petstore/jaxrs-cxf-client/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.1-SNAPSHOT \ No newline at end of file +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/jaxrs-cxf-client/pom.xml b/samples/client/petstore/jaxrs-cxf-client/pom.xml index 2a3b7a5ed31a..1ec025434d5b 100644 --- a/samples/client/petstore/jaxrs-cxf-client/pom.xml +++ b/samples/client/petstore/jaxrs-cxf-client/pom.xml @@ -2,7 +2,7 @@ 4.0.0 io.swagger jaxrs-cxf-petstore-client - war + jar jaxrs-cxf-petstore-client This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. 1.0.0 @@ -33,7 +33,7 @@ 8079 stopit - 8080 + 60000 @@ -77,15 +77,6 @@ - - - - maven-war-plugin - 3.1.0 - - false - - @@ -113,13 +104,6 @@ ${junit-version} test - - - javax.validation - validation-api - ${beanvalidation-version} - provided - org.apache.cxf @@ -141,12 +125,6 @@ ${cxf-version} compile - - org.apache.cxf - cxf-rt-rs-service-description-swagger - ${cxf-version} - compile - org.apache.cxf cxf-rt-ws-policy @@ -166,10 +144,9 @@ compile - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson-jaxrs-version} - compile + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-jaxrs-version} @@ -190,7 +167,6 @@ 4.12 1.1.7 2.5 - 1.1.0.Final 3.2.1 2.9.1 UTF-8 diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/PetApi.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/PetApi.java index f8b8a10d2886..69c01301f41b 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/PetApi.java @@ -18,8 +18,6 @@ import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponse; import io.swagger.jaxrs.PATCH; -import javax.validation.constraints.*; -import javax.validation.Valid; /** * Swagger Petstore @@ -41,10 +39,10 @@ public interface PetApi { @Path("/pet") @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Add a new pet to the store", tags={ "pet", }) + @ApiOperation(value = "Add a new pet to the store", tags={ }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) - public void addPet(@Valid Pet body); + public void addPet(Pet body); /** * Deletes a pet @@ -55,7 +53,7 @@ public interface PetApi { @DELETE @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Deletes a pet", tags={ "pet", }) + @ApiOperation(value = "Deletes a pet", tags={ }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value") }) public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); @@ -69,11 +67,11 @@ public interface PetApi { @GET @Path("/pet/findByStatus") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Finds Pets by status", tags={ "pet", }) + @ApiOperation(value = "Finds Pets by status", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @ApiResponse(code = 400, message = "Invalid status value") }) - public List findPetsByStatus(@QueryParam("status") @NotNull List status); + public List findPetsByStatus(@QueryParam("status")List status); /** * Finds Pets by tags @@ -84,11 +82,11 @@ public interface PetApi { @GET @Path("/pet/findByTags") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Finds Pets by tags", tags={ "pet", }) + @ApiOperation(value = "Finds Pets by tags", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @ApiResponse(code = 400, message = "Invalid tag value") }) - public List findPetsByTags(@QueryParam("tags") @NotNull List tags); + public List findPetsByTags(@QueryParam("tags")List tags); /** * Find pet by ID @@ -99,7 +97,7 @@ public interface PetApi { @GET @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Find pet by ID", tags={ "pet", }) + @ApiOperation(value = "Find pet by ID", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied"), @@ -116,12 +114,12 @@ public interface PetApi { @Path("/pet") @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Update an existing pet", tags={ "pet", }) + @ApiOperation(value = "Update an existing pet", tags={ }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Pet not found"), @ApiResponse(code = 405, message = "Validation exception") }) - public void updatePet(@Valid Pet body); + public void updatePet(Pet body); /** * Updates a pet in the store with form data @@ -133,7 +131,7 @@ public interface PetApi { @Path("/pet/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Updates a pet in the store with form data", tags={ "pet", }) + @ApiOperation(value = "Updates a pet in the store with form data", tags={ }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); @@ -148,7 +146,7 @@ public interface PetApi { @Path("/pet/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) @Produces({ "application/json" }) - @ApiOperation(value = "uploads an image", tags={ "pet" }) + @ApiOperation(value = "uploads an image", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) public ModelApiResponse uploadFile(@PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file" , required = false) Attachment fileDetail); diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/StoreApi.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/StoreApi.java index 72508ea286ab..c62b8f5f1dd9 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/StoreApi.java @@ -1,6 +1,5 @@ package io.swagger.api; -import java.util.Map; import io.swagger.model.Order; import java.io.InputStream; @@ -17,8 +16,6 @@ import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponse; import io.swagger.jaxrs.PATCH; -import javax.validation.constraints.*; -import javax.validation.Valid; /** * Swagger Petstore @@ -39,7 +36,7 @@ public interface StoreApi { @DELETE @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Delete purchase order by ID", tags={ "store", }) + @ApiOperation(value = "Delete purchase order by ID", tags={ }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Order not found") }) @@ -54,7 +51,7 @@ public interface StoreApi { @GET @Path("/store/inventory") @Produces({ "application/json" }) - @ApiOperation(value = "Returns pet inventories by status", tags={ "store", }) + @ApiOperation(value = "Returns pet inventories by status", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") }) public Map getInventory(); @@ -68,12 +65,12 @@ public interface StoreApi { @GET @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Find purchase order by ID", tags={ "store", }) + @ApiOperation(value = "Find purchase order by ID", tags={ }) @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") }) - public Order getOrderById(@PathParam("orderId") @Min(1) @Max(5) Long orderId); + public Order getOrderById(@PathParam("orderId") Long orderId); /** * Place an order for a pet @@ -84,10 +81,10 @@ public interface StoreApi { @POST @Path("/store/order") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Place an order for a pet", tags={ "store" }) + @ApiOperation(value = "Place an order for a pet", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order") }) - public Order placeOrder(@Valid Order body); + public Order placeOrder(Order body); } diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/UserApi.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/UserApi.java index 7aba6911b466..b88df3d09a78 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/UserApi.java @@ -1,6 +1,5 @@ package io.swagger.api; -import java.util.List; import io.swagger.model.User; import java.io.InputStream; @@ -17,8 +16,6 @@ import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponse; import io.swagger.jaxrs.PATCH; -import javax.validation.constraints.*; -import javax.validation.Valid; /** * Swagger Petstore @@ -39,10 +36,10 @@ public interface UserApi { @POST @Path("/user") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Create user", tags={ "user", }) + @ApiOperation(value = "Create user", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUser(@Valid User body); + public void createUser(User body); /** * Creates list of users with given input array @@ -53,10 +50,10 @@ public interface UserApi { @POST @Path("/user/createWithArray") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + @ApiOperation(value = "Creates list of users with given input array", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUsersWithArrayInput(@Valid List body); + public void createUsersWithArrayInput(List body); /** * Creates list of users with given input array @@ -67,10 +64,10 @@ public interface UserApi { @POST @Path("/user/createWithList") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + @ApiOperation(value = "Creates list of users with given input array", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUsersWithListInput(@Valid List body); + public void createUsersWithListInput(List body); /** * Delete user @@ -81,7 +78,7 @@ public interface UserApi { @DELETE @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Delete user", tags={ "user", }) + @ApiOperation(value = "Delete user", tags={ }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @@ -96,7 +93,7 @@ public interface UserApi { @GET @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Get user by user name", tags={ "user", }) + @ApiOperation(value = "Get user by user name", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied"), @@ -112,11 +109,11 @@ public interface UserApi { @GET @Path("/user/login") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Logs user into the system", tags={ "user", }) + @ApiOperation(value = "Logs user into the system", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied") }) - public String loginUser(@QueryParam("username") @NotNull String username, @QueryParam("password") @NotNull String password); + public String loginUser(@QueryParam("username")String username, @QueryParam("password")String password); /** * Logs out current logged in user session @@ -127,7 +124,7 @@ public interface UserApi { @GET @Path("/user/logout") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Logs out current logged in user session", tags={ "user", }) + @ApiOperation(value = "Logs out current logged in user session", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) public void logoutUser(); @@ -141,10 +138,10 @@ public interface UserApi { @PUT @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Updated user", tags={ "user" }) + @ApiOperation(value = "Updated user", tags={ }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid user supplied"), @ApiResponse(code = 404, message = "User not found") }) - public void updateUser(@PathParam("username") String username, @Valid User body); + public void updateUser(@PathParam("username") String username, User body); } diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Category.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Category.java index 0e190cbe457c..a718f7f60e6d 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Category.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Category.java @@ -1,7 +1,6 @@ package io.swagger.model; import io.swagger.annotations.ApiModel; -import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/ModelApiResponse.java index c6aab8b6a074..be82193b3088 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -1,7 +1,6 @@ package io.swagger.model; import io.swagger.annotations.ApiModel; -import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Order.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Order.java index 973b0260b368..9c1c79300cb4 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Order.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Order.java @@ -2,7 +2,6 @@ import io.swagger.annotations.ApiModel; import java.util.Date; -import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Pet.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Pet.java index 6e3fcf954ecc..7c24a892298e 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Pet.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Pet.java @@ -5,7 +5,6 @@ import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; -import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -117,7 +116,6 @@ public Pet category(Category category) { * @return name **/ @JsonProperty("name") - @NotNull public String getName() { return name; } @@ -136,7 +134,6 @@ public Pet name(String name) { * @return photoUrls **/ @JsonProperty("photoUrls") - @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Tag.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Tag.java index 71801d143d33..4f6240b5be74 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Tag.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Tag.java @@ -1,7 +1,6 @@ package io.swagger.model; import io.swagger.annotations.ApiModel; -import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/User.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/User.java index e7d2773ea703..a2a336d3e94f 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/User.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/User.java @@ -1,7 +1,6 @@ package io.swagger.model; import io.swagger.annotations.ApiModel; -import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/client/petstore/jaxrs-cxf-client/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/client/petstore/jaxrs-cxf-client/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java deleted file mode 100644 index d9b9345d3396..000000000000 --- a/samples/client/petstore/jaxrs-cxf-client/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import java.io.File; -import io.swagger.model.ModelApiResponse; -import io.swagger.model.Pet; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; -import org.apache.cxf.jaxrs.model.wadl.Description; -import org.apache.cxf.jaxrs.model.wadl.DocTarget; - -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; - -public class PetApiServiceImpl implements PetApi { - public void addPet(Pet body) { - // TODO: Implement... - - - } - - public void deletePet(Long petId, String apiKey) { - // TODO: Implement... - - - } - - public List findPetsByStatus(List status) { - // TODO: Implement... - - return null; - } - - public List findPetsByTags(List tags) { - // TODO: Implement... - - return null; - } - - public Pet getPetById(Long petId) { - // TODO: Implement... - - return null; - } - - public void updatePet(Pet body) { - // TODO: Implement... - - - } - - public void updatePetWithForm(Long petId, String name, String status) { - // TODO: Implement... - - - } - - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, Attachment fileDetail) { - // TODO: Implement... - - return null; - } - -} - diff --git a/samples/client/petstore/jaxrs-cxf-client/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/client/petstore/jaxrs-cxf-client/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java deleted file mode 100644 index 3f791097b6b1..000000000000 --- a/samples/client/petstore/jaxrs-cxf-client/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import java.util.Map; -import io.swagger.model.Order; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; -import org.apache.cxf.jaxrs.model.wadl.Description; -import org.apache.cxf.jaxrs.model.wadl.DocTarget; - -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; - -public class StoreApiServiceImpl implements StoreApi { - public void deleteOrder(String orderId) { - // TODO: Implement... - - - } - - public Map getInventory() { - // TODO: Implement... - - return null; - } - - public Order getOrderById(Long orderId) { - // TODO: Implement... - - return null; - } - - public Order placeOrder(Order body) { - // TODO: Implement... - - return null; - } - -} - diff --git a/samples/client/petstore/jaxrs-cxf-client/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/client/petstore/jaxrs-cxf-client/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java deleted file mode 100644 index 861273cfb7b4..000000000000 --- a/samples/client/petstore/jaxrs-cxf-client/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import java.util.List; -import io.swagger.model.User; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; -import org.apache.cxf.jaxrs.model.wadl.Description; -import org.apache.cxf.jaxrs.model.wadl.DocTarget; - -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; - -public class UserApiServiceImpl implements UserApi { - public void createUser(User body) { - // TODO: Implement... - - - } - - public void createUsersWithArrayInput(List body) { - // TODO: Implement... - - - } - - public void createUsersWithListInput(List body) { - // TODO: Implement... - - - } - - public void deleteUser(String username) { - // TODO: Implement... - - - } - - public User getUserByName(String username) { - // TODO: Implement... - - return null; - } - - public String loginUser(String username, String password) { - // TODO: Implement... - - return null; - } - - public void logoutUser() { - // TODO: Implement... - - - } - - public void updateUser(String username, User body) { - // TODO: Implement... - - - } - -} - diff --git a/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/PetApiTest.java b/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/PetApiTest.java index b7a13f768495..95743b0f9654 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/PetApiTest.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/PetApiTest.java @@ -49,7 +49,11 @@ /** - * API tests for PetApi + * Swagger Petstore + * + *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * API tests for PetApi */ public class PetApiTest { diff --git a/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/StoreApiTest.java b/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/StoreApiTest.java index 92bb0e8b8f93..f4a896089029 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/StoreApiTest.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/StoreApiTest.java @@ -25,7 +25,6 @@ package io.swagger.api; -import java.util.Map; import io.swagger.model.Order; import org.junit.Test; import org.junit.Before; @@ -48,7 +47,11 @@ /** - * API tests for StoreApi + * Swagger Petstore + * + *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * API tests for StoreApi */ public class StoreApiTest { diff --git a/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/UserApiTest.java b/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/UserApiTest.java index a0ecb1dbee2a..afccde9fe274 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/UserApiTest.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/test/java/io/swagger/api/UserApiTest.java @@ -25,7 +25,6 @@ package io.swagger.api; -import java.util.List; import io.swagger.model.User; import org.junit.Test; import org.junit.Before; @@ -48,7 +47,11 @@ /** - * API tests for UserApi + * Swagger Petstore + * + *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * API tests for UserApi */ public class UserApiTest { diff --git a/samples/client/petstore/jmeter/PetApi.jmx b/samples/client/petstore/jmeter/PetApi.jmx index c61a96b600ee..8e36592e32c5 100644 --- a/samples/client/petstore/jmeter/PetApi.jmx +++ b/samples/client/petstore/jmeter/PetApi.jmx @@ -6,24 +6,28 @@ false false - - - host - localhost - = - - - port - 8080 - = - - + + + threads + ${__P(threads,1)} + = + + + rampup + ${__P(rampup,1)} + = + + + duration + ${__P(duration,1)} + = + testCases ${__P(testCases,10)} @@ -102,13 +106,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -133,7 +137,7 @@ false true false - HttpClient3.1 + false Add a new pet to the store @@ -145,9 +149,10 @@ ${testData.addPetFile} true true - shareMode.all + shareMode.group false + true @@ -167,13 +172,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -202,7 +207,7 @@ false true false - HttpClient3.1 + false Deletes a pet @@ -214,9 +219,10 @@ ${testData.deletePetFile} true true - shareMode.all + shareMode.group false + true @@ -236,13 +242,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -274,7 +280,7 @@ false true false - HttpClient3.1 + false Finds Pets by status Multiple status values can be provided with comma separated strings @@ -286,9 +292,10 @@ ${testData.findPetsByStatusFile} true true - shareMode.all + shareMode.group false + true @@ -308,13 +315,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -346,7 +353,7 @@ false true false - HttpClient3.1 + false Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -358,9 +365,10 @@ ${testData.findPetsByTagsFile} true true - shareMode.all + shareMode.group false + true @@ -380,13 +388,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -411,7 +419,7 @@ false true false - HttpClient3.1 + false Find pet by ID Returns a single pet @@ -423,9 +431,10 @@ ${testData.getPetByIdFile} true true - shareMode.all + shareMode.group false + true @@ -445,13 +454,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -476,7 +485,7 @@ false true false - HttpClient3.1 + false Update an existing pet @@ -488,9 +497,10 @@ ${testData.updatePetFile} true true - shareMode.all + shareMode.group false + true @@ -510,13 +520,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -541,7 +551,7 @@ false true false - HttpClient3.1 + false Updates a pet in the store with form data @@ -553,9 +563,10 @@ ${testData.updatePetWithFormFile} true true - shareMode.all + shareMode.group false + true @@ -575,13 +586,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -606,7 +617,7 @@ false true false - HttpClient3.1 + false uploads an image @@ -618,9 +629,10 @@ ${testData.uploadFileFile} true true - shareMode.all + shareMode.group false + true diff --git a/samples/client/petstore/jmeter/StoreApi.jmx b/samples/client/petstore/jmeter/StoreApi.jmx index 07003622bba3..21eb7f3059d7 100644 --- a/samples/client/petstore/jmeter/StoreApi.jmx +++ b/samples/client/petstore/jmeter/StoreApi.jmx @@ -6,24 +6,28 @@ false false - - - host - localhost - = - - - port - 8080 - = - - + + + threads + ${__P(threads,1)} + = + + + rampup + ${__P(rampup,1)} + = + + + duration + ${__P(duration,1)} + = + testCases ${__P(testCases,10)} @@ -82,13 +86,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -113,7 +117,7 @@ false true false - HttpClient3.1 + false Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -125,9 +129,10 @@ ${testData.deleteOrderFile} true true - shareMode.all + shareMode.group false + true @@ -147,13 +152,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -178,7 +183,7 @@ false true false - HttpClient3.1 + false Returns pet inventories by status Returns a map of status codes to quantities @@ -190,9 +195,10 @@ ${testData.getInventoryFile} true true - shareMode.all + shareMode.group false + true @@ -212,13 +218,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -243,7 +249,7 @@ false true false - HttpClient3.1 + false Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -255,9 +261,10 @@ ${testData.getOrderByIdFile} true true - shareMode.all + shareMode.group false + true @@ -277,13 +284,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -308,7 +315,7 @@ false true false - HttpClient3.1 + false Place an order for a pet @@ -320,9 +327,10 @@ ${testData.placeOrderFile} true true - shareMode.all + shareMode.group false + true diff --git a/samples/client/petstore/jmeter/UserApi.jmx b/samples/client/petstore/jmeter/UserApi.jmx index 5375a419a053..2dd7aee906e2 100644 --- a/samples/client/petstore/jmeter/UserApi.jmx +++ b/samples/client/petstore/jmeter/UserApi.jmx @@ -6,24 +6,28 @@ false false - - - host - localhost - = - - - port - 8080 - = - - + + + threads + ${__P(threads,1)} + = + + + rampup + ${__P(rampup,1)} + = + + + duration + ${__P(duration,1)} + = + testCases ${__P(testCases,10)} @@ -102,13 +106,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -133,7 +137,7 @@ false true false - HttpClient3.1 + false Create user This can only be done by the logged in user. @@ -145,9 +149,10 @@ ${testData.createUserFile} true true - shareMode.all + shareMode.group false + true @@ -167,13 +172,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -198,7 +203,7 @@ false true false - HttpClient3.1 + false Creates list of users with given input array @@ -210,9 +215,10 @@ ${testData.createUsersWithArrayInputFile} true true - shareMode.all + shareMode.group false + true @@ -232,13 +238,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -263,7 +269,7 @@ false true false - HttpClient3.1 + false Creates list of users with given input array @@ -275,9 +281,10 @@ ${testData.createUsersWithListInputFile} true true - shareMode.all + shareMode.group false + true @@ -297,13 +304,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -328,7 +335,7 @@ false true false - HttpClient3.1 + false Delete user This can only be done by the logged in user. @@ -340,9 +347,10 @@ ${testData.deleteUserFile} true true - shareMode.all + shareMode.group false + true @@ -362,13 +370,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -393,7 +401,7 @@ false true false - HttpClient3.1 + false Get user by user name @@ -405,9 +413,10 @@ ${testData.getUserByNameFile} true true - shareMode.all + shareMode.group false + true @@ -427,13 +436,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -472,7 +481,7 @@ false true false - HttpClient3.1 + false Logs user into the system @@ -484,9 +493,10 @@ ${testData.loginUserFile} true true - shareMode.all + shareMode.group false + true @@ -506,13 +516,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -537,7 +547,7 @@ false true false - HttpClient3.1 + false Logs out current logged in user session @@ -549,9 +559,10 @@ ${testData.logoutUserFile} true true - shareMode.all + shareMode.group false + true @@ -571,13 +582,13 @@ false ${testCases} - 1 - 1 + ${threads} + ${rampup} 1448391617000 1448391617000 - false - - + true + ${duration} + 5 @@ -602,7 +613,7 @@ false true false - HttpClient3.1 + false Updated user This can only be done by the logged in user. @@ -614,9 +625,10 @@ ${testData.updateUserFile} true true - shareMode.all + shareMode.group false + true diff --git a/samples/client/petstore/kotlin-string/docs/UserApi.md b/samples/client/petstore/kotlin-string/docs/UserApi.md index d15aae23da39..0c4b9b79de84 100644 --- a/samples/client/petstore/kotlin-string/docs/UserApi.md +++ b/samples/client/petstore/kotlin-string/docs/UserApi.md @@ -213,7 +213,7 @@ Get user by user name //import io.swagger.client.models.* val apiInstance = UserApi() -val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. +val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. try { val result : User = apiInstance.getUserByName(username) println(result) @@ -230,7 +230,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | + **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | ### Return type diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/apis/UserApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/apis/UserApi.kt index d3d80fe76ab6..9bd50f0f4c0f 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/apis/UserApi.kt @@ -144,7 +144,7 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ @Suppress("UNCHECKED_CAST") diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt index da1787506887..7e3a11664bd0 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt @@ -12,7 +12,12 @@ open class ApiClient(val baseUrl: String) { protected val XmlMediaType = "application/xml" @JvmStatic - val client : OkHttpClient = OkHttpClient() + val client by lazy { + builder.build() + } + + @JvmStatic + val builder: OkHttpClient.Builder = OkHttpClient.Builder() @JvmStatic var defaultHeaders: Map by ApplicationDelegates.setOnce(mapOf(ContentType to JsonMediaType, Accept to JsonMediaType)) @@ -85,9 +90,9 @@ open class ApiClient(val baseUrl: String) { RequestMethod.DELETE -> Request.Builder().url(url).delete() RequestMethod.GET -> Request.Builder().url(url) RequestMethod.HEAD -> Request.Builder().url(url).head() - RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(body!!, contentType)) - RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body!!, contentType)) - RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body!!, contentType)) + RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(body, contentType)) + RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body, contentType)) + RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body, contentType)) RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null) } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/models/Order.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/models/Order.kt index 043ffe9baf16..98b2a75b05d2 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/models/Order.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/models/Order.kt @@ -12,6 +12,7 @@ package io.swagger.client.models +import com.squareup.moshi.Json /** * An order for a pets from the pet store * @param id @@ -35,13 +36,13 @@ data class Order ( * Order Status * Values: placed,approved,delivered */ - enum class Status(val value: kotlin.Any){ + enum class Status(val value: kotlin.String){ - placed("placed"), + @Json(name = "placed") placed("placed"), - approved("approved"), + @Json(name = "approved") approved("approved"), - delivered("delivered"); + @Json(name = "delivered") delivered("delivered"); } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/models/Pet.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/models/Pet.kt index c507522da923..4008a46203c9 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/io/swagger/client/models/Pet.kt @@ -14,6 +14,7 @@ package io.swagger.client.models import io.swagger.client.models.Category import io.swagger.client.models.Tag +import com.squareup.moshi.Json /** * A pet for sale in the pet store * @param id @@ -37,13 +38,13 @@ data class Pet ( * pet status in the store * Values: available,pending,sold */ - enum class Status(val value: kotlin.Any){ + enum class Status(val value: kotlin.String){ - available("available"), + @Json(name = "available") available("available"), - pending("pending"), + @Json(name = "pending") pending("pending"), - sold("sold"); + @Json(name = "sold") sold("sold"); } diff --git a/samples/client/petstore/kotlin-threetenbp/docs/UserApi.md b/samples/client/petstore/kotlin-threetenbp/docs/UserApi.md index d15aae23da39..0c4b9b79de84 100644 --- a/samples/client/petstore/kotlin-threetenbp/docs/UserApi.md +++ b/samples/client/petstore/kotlin-threetenbp/docs/UserApi.md @@ -213,7 +213,7 @@ Get user by user name //import io.swagger.client.models.* val apiInstance = UserApi() -val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. +val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. try { val result : User = apiInstance.getUserByName(username) println(result) @@ -230,7 +230,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | + **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | ### Return type diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/apis/UserApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/apis/UserApi.kt index 3d2dabddad70..a7c647ce1e1a 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/apis/UserApi.kt @@ -145,7 +145,7 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ @Suppress("UNCHECKED_CAST") diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt index da1787506887..7e3a11664bd0 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt @@ -12,7 +12,12 @@ open class ApiClient(val baseUrl: String) { protected val XmlMediaType = "application/xml" @JvmStatic - val client : OkHttpClient = OkHttpClient() + val client by lazy { + builder.build() + } + + @JvmStatic + val builder: OkHttpClient.Builder = OkHttpClient.Builder() @JvmStatic var defaultHeaders: Map by ApplicationDelegates.setOnce(mapOf(ContentType to JsonMediaType, Accept to JsonMediaType)) @@ -85,9 +90,9 @@ open class ApiClient(val baseUrl: String) { RequestMethod.DELETE -> Request.Builder().url(url).delete() RequestMethod.GET -> Request.Builder().url(url) RequestMethod.HEAD -> Request.Builder().url(url).head() - RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(body!!, contentType)) - RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body!!, contentType)) - RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body!!, contentType)) + RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(body, contentType)) + RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body, contentType)) + RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body, contentType)) RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null) } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/models/Order.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/models/Order.kt index e8a67e55bf92..ced79e3553c6 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/models/Order.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/models/Order.kt @@ -13,6 +13,7 @@ package io.swagger.client.models import org.threeten.bp.LocalDateTime +import com.squareup.moshi.Json /** * An order for a pets from the pet store * @param id @@ -36,13 +37,13 @@ data class Order ( * Order Status * Values: placed,approved,delivered */ - enum class Status(val value: kotlin.Any){ + enum class Status(val value: kotlin.String){ - placed("placed"), + @Json(name = "placed") placed("placed"), - approved("approved"), + @Json(name = "approved") approved("approved"), - delivered("delivered"); + @Json(name = "delivered") delivered("delivered"); } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/models/Pet.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/models/Pet.kt index 5ba0d7c63092..df45756efac3 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/io/swagger/client/models/Pet.kt @@ -15,6 +15,7 @@ import io.swagger.client.models.Category import io.swagger.client.models.Tag import org.threeten.bp.LocalDateTime +import com.squareup.moshi.Json /** * A pet for sale in the pet store * @param id @@ -38,13 +39,13 @@ data class Pet ( * pet status in the store * Values: available,pending,sold */ - enum class Status(val value: kotlin.Any){ + enum class Status(val value: kotlin.String){ - available("available"), + @Json(name = "available") available("available"), - pending("pending"), + @Json(name = "pending") pending("pending"), - sold("sold"); + @Json(name = "sold") sold("sold"); } diff --git a/samples/client/petstore/kotlin/docs/UserApi.md b/samples/client/petstore/kotlin/docs/UserApi.md index d15aae23da39..0c4b9b79de84 100644 --- a/samples/client/petstore/kotlin/docs/UserApi.md +++ b/samples/client/petstore/kotlin/docs/UserApi.md @@ -213,7 +213,7 @@ Get user by user name //import io.swagger.client.models.* val apiInstance = UserApi() -val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. +val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. try { val result : User = apiInstance.getUserByName(username) println(result) @@ -230,7 +230,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | + **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | ### Return type diff --git a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/apis/UserApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/apis/UserApi.kt index d3d80fe76ab6..9bd50f0f4c0f 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/apis/UserApi.kt @@ -144,7 +144,7 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ @Suppress("UNCHECKED_CAST") diff --git a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt index eb13afafce65..7e3a11664bd0 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt @@ -12,7 +12,12 @@ open class ApiClient(val baseUrl: String) { protected val XmlMediaType = "application/xml" @JvmStatic - val client : OkHttpClient = OkHttpClient() + val client by lazy { + builder.build() + } + + @JvmStatic + val builder: OkHttpClient.Builder = OkHttpClient.Builder() @JvmStatic var defaultHeaders: Map by ApplicationDelegates.setOnce(mapOf(ContentType to JsonMediaType, Accept to JsonMediaType)) diff --git a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Order.kt b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Order.kt index 78afb772e9a2..718a31cd0d34 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Order.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Order.kt @@ -12,6 +12,7 @@ package io.swagger.client.models +import com.squareup.moshi.Json /** * An order for a pets from the pet store * @param id @@ -37,11 +38,11 @@ data class Order ( */ enum class Status(val value: kotlin.String){ - placed("placed"), + @Json(name = "placed") placed("placed"), - approved("approved"), + @Json(name = "approved") approved("approved"), - delivered("delivered"); + @Json(name = "delivered") delivered("delivered"); } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Pet.kt b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Pet.kt index 8c0256b3be8e..4008a46203c9 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Pet.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Pet.kt @@ -14,6 +14,7 @@ package io.swagger.client.models import io.swagger.client.models.Category import io.swagger.client.models.Tag +import com.squareup.moshi.Json /** * A pet for sale in the pet store * @param id @@ -39,11 +40,11 @@ data class Pet ( */ enum class Status(val value: kotlin.String){ - available("available"), + @Json(name = "available") available("available"), - pending("pending"), + @Json(name = "pending") pending("pending"), - sold("sold"); + @Json(name = "sold") sold("sold"); } diff --git a/samples/client/petstore/lua/.swagger-codegen/VERSION b/samples/client/petstore/lua/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/lua/.swagger-codegen/VERSION +++ b/samples/client/petstore/lua/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/lua/petstore/api/pet_api.lua b/samples/client/petstore/lua/petstore/api/pet_api.lua index f9de7e39135a..620f5afac389 100644 --- a/samples/client/petstore/lua/petstore/api/pet_api.lua +++ b/samples/client/petstore/lua/petstore/api/pet_api.lua @@ -43,7 +43,7 @@ local function new_pet_api(host, basePath, schemes) }, pet_api_mt) end -function pet_api:add_pet(body) +function pet_api:add_pet(pet) local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; @@ -53,17 +53,7 @@ function pet_api:add_pet(body) -- set HTTP verb req.headers:upsert(":method", "POST") - -- TODO: create a function to select proper accept - -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_content_type = { "application/json", "application/xml" } - req.headers:upsert("accept", "application/json") - - -- TODO: create a function to select proper content-type - -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_accept = { "application/xml", "application/json" } - req.headers:upsert("content-type", "application/xml") - - req:set_body(dkjson.encode(body)) + req:set_body(dkjson.encode(pet)) -- oAuth if self.access_token then @@ -99,11 +89,6 @@ function pet_api:delete_pet(pet_id, api_key) -- set HTTP verb req.headers:upsert(":method", "DELETE") - -- TODO: create a function to select proper content-type - -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_accept = { "application/xml", "application/json" } - req.headers:upsert("content-type", "application/xml") - if api_key then req.headers:upsert("api_key", api_key) end @@ -287,7 +272,7 @@ function pet_api:get_pet_by_id(pet_id) end end -function pet_api:update_pet(body) +function pet_api:update_pet(pet) local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; @@ -297,17 +282,7 @@ function pet_api:update_pet(body) -- set HTTP verb req.headers:upsert(":method", "PUT") - -- TODO: create a function to select proper accept - -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_content_type = { "application/json", "application/xml" } - req.headers:upsert("accept", "application/json") - - -- TODO: create a function to select proper content-type - -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_accept = { "application/xml", "application/json" } - req.headers:upsert("content-type", "application/xml") - - req:set_body(dkjson.encode(body)) + req:set_body(dkjson.encode(pet)) -- oAuth if self.access_token then @@ -348,11 +323,6 @@ function pet_api:update_pet_with_form(pet_id, name, status) --local var_content_type = { "application/x-www-form-urlencoded" } req.headers:upsert("accept", "application/x-www-form-urlencoded") - -- TODO: create a function to select proper content-type - -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_accept = { "application/xml", "application/json" } - req.headers:upsert("content-type", "application/xml") - req:set_body(http_util.dict_to_query({ ["name"] = name; ["status"] = status; diff --git a/samples/client/petstore/lua/petstore/api/store_api.lua b/samples/client/petstore/lua/petstore/api/store_api.lua index 96927a16f9c5..cbec3b0fcc0b 100644 --- a/samples/client/petstore/lua/petstore/api/store_api.lua +++ b/samples/client/petstore/lua/petstore/api/store_api.lua @@ -52,11 +52,6 @@ function store_api:delete_order(order_id) -- set HTTP verb req.headers:upsert(":method", "DELETE") - -- TODO: create a function to select proper content-type - -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_accept = { "application/xml", "application/json" } - req.headers:upsert("content-type", "application/xml") - -- make the HTTP call local headers, stream, errno = req:go() @@ -173,7 +168,7 @@ function store_api:get_order_by_id(order_id) end end -function store_api:place_order(body) +function store_api:place_order(order) local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; @@ -183,12 +178,17 @@ function store_api:place_order(body) -- set HTTP verb req.headers:upsert(":method", "POST") + -- TODO: create a function to select proper accept + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_content_type = { "application/json" } + req.headers:upsert("accept", "application/json") + -- TODO: create a function to select proper content-type -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 --local var_accept = { "application/xml", "application/json" } req.headers:upsert("content-type", "application/xml") - req:set_body(dkjson.encode(body)) + req:set_body(dkjson.encode(order)) -- make the HTTP call diff --git a/samples/client/petstore/lua/petstore/api/user_api.lua b/samples/client/petstore/lua/petstore/api/user_api.lua index 0369cf1e8bd4..62b9e576cb07 100644 --- a/samples/client/petstore/lua/petstore/api/user_api.lua +++ b/samples/client/petstore/lua/petstore/api/user_api.lua @@ -42,7 +42,7 @@ local function new_user_api(host, basePath, schemes) }, user_api_mt) end -function user_api:create_user(body) +function user_api:create_user(user) local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; @@ -52,12 +52,12 @@ function user_api:create_user(body) -- set HTTP verb req.headers:upsert(":method", "POST") - -- TODO: create a function to select proper content-type + -- TODO: create a function to select proper accept -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_accept = { "application/xml", "application/json" } - req.headers:upsert("content-type", "application/xml") + --local var_content_type = { "application/json" } + req.headers:upsert("accept", "application/json") - req:set_body(dkjson.encode(body)) + req:set_body(dkjson.encode(user)) -- make the HTTP call @@ -79,7 +79,7 @@ function user_api:create_user(body) end end -function user_api:create_users_with_array_input(body) +function user_api:create_users_with_array_input(user) local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; @@ -89,12 +89,7 @@ function user_api:create_users_with_array_input(body) -- set HTTP verb req.headers:upsert(":method", "POST") - -- TODO: create a function to select proper content-type - -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_accept = { "application/xml", "application/json" } - req.headers:upsert("content-type", "application/xml") - - req:set_body(dkjson.encode(body)) + req:set_body(dkjson.encode(user)) -- make the HTTP call @@ -116,7 +111,7 @@ function user_api:create_users_with_array_input(body) end end -function user_api:create_users_with_list_input(body) +function user_api:create_users_with_list_input(user) local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; @@ -126,12 +121,7 @@ function user_api:create_users_with_list_input(body) -- set HTTP verb req.headers:upsert(":method", "POST") - -- TODO: create a function to select proper content-type - -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_accept = { "application/xml", "application/json" } - req.headers:upsert("content-type", "application/xml") - - req:set_body(dkjson.encode(body)) + req:set_body(dkjson.encode(user)) -- make the HTTP call @@ -163,11 +153,6 @@ function user_api:delete_user(username) -- set HTTP verb req.headers:upsert(":method", "DELETE") - -- TODO: create a function to select proper content-type - -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_accept = { "application/xml", "application/json" } - req.headers:upsert("content-type", "application/xml") - -- make the HTTP call local headers, stream, errno = req:go() @@ -290,11 +275,6 @@ function user_api:logout_user() -- set HTTP verb req.headers:upsert(":method", "GET") - -- TODO: create a function to select proper content-type - -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_accept = { "application/xml", "application/json" } - req.headers:upsert("content-type", "application/xml") - -- make the HTTP call local headers, stream, errno = req:go() @@ -315,7 +295,7 @@ function user_api:logout_user() end end -function user_api:update_user(username, body) +function user_api:update_user(username, user) local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; @@ -325,12 +305,12 @@ function user_api:update_user(username, body) -- set HTTP verb req.headers:upsert(":method", "PUT") - -- TODO: create a function to select proper content-type + -- TODO: create a function to select proper accept -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 - --local var_accept = { "application/xml", "application/json" } - req.headers:upsert("content-type", "application/xml") + --local var_content_type = { "application/json" } + req.headers:upsert("accept", "application/json") - req:set_body(dkjson.encode(body)) + req:set_body(dkjson.encode(user)) -- make the HTTP call diff --git a/samples/client/petstore/perl/.swagger-codegen/VERSION b/samples/client/petstore/perl/.swagger-codegen/VERSION index f9f7450d1359..096bf47efe31 100644 --- a/samples/client/petstore/perl/.swagger-codegen/VERSION +++ b/samples/client/petstore/perl/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index ba89cad42145..9d77ab4e7332 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -10,7 +10,7 @@ Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/ - API version: 1.0.0 - Package version: 1.0.0 -- Build package: io.swagger.codegen.languages.PerlClientCodegen +- Build package: org.openapitools.codegen.languages.PerlClientCodegen ## A note on Moose @@ -240,9 +240,11 @@ use WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayTest; use WWW::SwaggerClient::Object::Capitalization; +use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; use WWW::SwaggerClient::Object::ClassModel; use WWW::SwaggerClient::Object::Client; +use WWW::SwaggerClient::Object::Dog; use WWW::SwaggerClient::Object::EnumArrays; use WWW::SwaggerClient::Object::EnumClass; use WWW::SwaggerClient::Object::EnumTest; @@ -266,8 +268,6 @@ use WWW::SwaggerClient::Object::ReadOnlyFirst; use WWW::SwaggerClient::Object::SpecialModelName; use WWW::SwaggerClient::Object::Tag; use WWW::SwaggerClient::Object::User; -use WWW::SwaggerClient::Object::Cat; -use WWW::SwaggerClient::Object::Dog; ```` @@ -295,9 +295,11 @@ use WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayTest; use WWW::SwaggerClient::Object::Capitalization; +use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; use WWW::SwaggerClient::Object::ClassModel; use WWW::SwaggerClient::Object::Client; +use WWW::SwaggerClient::Object::Dog; use WWW::SwaggerClient::Object::EnumArrays; use WWW::SwaggerClient::Object::EnumClass; use WWW::SwaggerClient::Object::EnumTest; @@ -321,8 +323,6 @@ use WWW::SwaggerClient::Object::ReadOnlyFirst; use WWW::SwaggerClient::Object::SpecialModelName; use WWW::SwaggerClient::Object::Tag; use WWW::SwaggerClient::Object::User; -use WWW::SwaggerClient::Object::Cat; -use WWW::SwaggerClient::Object::Dog; # for displaying the API response data use Data::Dumper; @@ -331,10 +331,10 @@ use WWW::SwaggerClient::; my $api_instance = WWW::SwaggerClient::->new( ); -my $body = WWW::SwaggerClient::Object::Client->new(); # Client | client model +my $client = WWW::SwaggerClient::Object::Client->new(); # Client | client model eval { - my $result = $api_instance->test_special_tags(body => $body); + my $result = $api_instance->test_special_tags(client => $client); print Dumper($result); }; if ($@) { @@ -354,9 +354,11 @@ Class | Method | HTTP request | Description *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 | *FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | +*FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | *FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data *FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store @@ -390,9 +392,11 @@ Class | Method | HTTP request | Description - [WWW::SwaggerClient::Object::ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [WWW::SwaggerClient::Object::ArrayTest](docs/ArrayTest.md) - [WWW::SwaggerClient::Object::Capitalization](docs/Capitalization.md) + - [WWW::SwaggerClient::Object::Cat](docs/Cat.md) - [WWW::SwaggerClient::Object::Category](docs/Category.md) - [WWW::SwaggerClient::Object::ClassModel](docs/ClassModel.md) - [WWW::SwaggerClient::Object::Client](docs/Client.md) + - [WWW::SwaggerClient::Object::Dog](docs/Dog.md) - [WWW::SwaggerClient::Object::EnumArrays](docs/EnumArrays.md) - [WWW::SwaggerClient::Object::EnumClass](docs/EnumClass.md) - [WWW::SwaggerClient::Object::EnumTest](docs/EnumTest.md) @@ -416,8 +420,6 @@ Class | Method | HTTP request | Description - [WWW::SwaggerClient::Object::SpecialModelName](docs/SpecialModelName.md) - [WWW::SwaggerClient::Object::Tag](docs/Tag.md) - [WWW::SwaggerClient::Object::User](docs/User.md) - - [WWW::SwaggerClient::Object::Cat](docs/Cat.md) - - [WWW::SwaggerClient::Object::Dog](docs/Dog.md) # DOCUMENTATION FOR AUTHORIZATION diff --git a/samples/client/petstore/perl/docs/AnotherfakeApi.md b/samples/client/petstore/perl/docs/AnotherfakeApi.md index c48958831845..d456932e6040 100644 --- a/samples/client/petstore/perl/docs/AnotherfakeApi.md +++ b/samples/client/petstore/perl/docs/AnotherfakeApi.md @@ -13,7 +13,7 @@ Method | HTTP request | Description # **test_special_tags** -> Client test_special_tags(body => $body) +> Client test_special_tags(client => $client) To test special tags @@ -26,10 +26,10 @@ use WWW::SwaggerClient::AnotherFakeApi; my $api_instance = WWW::SwaggerClient::AnotherFakeApi->new( ); -my $body = WWW::SwaggerClient::Object::Client->new(); # Client | client model +my $client = WWW::SwaggerClient::Object::Client->new(); # Client | client model eval { - my $result = $api_instance->test_special_tags(body => $body); + my $result = $api_instance->test_special_tags(client => $client); print Dumper($result); }; if ($@) { @@ -41,7 +41,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | + **client** | [**Client**](Client.md)| client model | ### Return type diff --git a/samples/client/petstore/perl/docs/Body4.md b/samples/client/petstore/perl/docs/Body4.md new file mode 100644 index 000000000000..78c6b6653053 --- /dev/null +++ b/samples/client/petstore/perl/docs/Body4.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::Body4 + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Body4; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**param** | **string** | field1 | +**param2** | **string** | field2 | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/EnumTest.md b/samples/client/petstore/perl/docs/EnumTest.md index 07cc4d9ebcea..3c233a59decd 100644 --- a/samples/client/petstore/perl/docs/EnumTest.md +++ b/samples/client/petstore/perl/docs/EnumTest.md @@ -9,6 +9,7 @@ use WWW::SwaggerClient::Object::EnumTest; Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **enum_string** | **string** | | [optional] +**enum_string_required** | **string** | | **enum_integer** | **int** | | [optional] **enum_number** | **double** | | [optional] **outer_enum** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/client/petstore/perl/docs/FakeApi.md b/samples/client/petstore/perl/docs/FakeApi.md index 2ac74f17f5d2..4909454a2c8a 100644 --- a/samples/client/petstore/perl/docs/FakeApi.md +++ b/samples/client/petstore/perl/docs/FakeApi.md @@ -13,14 +13,16 @@ Method | HTTP request | Description [**fake_outer_composite_serialize**](FakeApi.md#fake_outer_composite_serialize) | **POST** /fake/outer/composite | [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | +[**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data # **fake_outer_boolean_serialize** -> OuterBoolean fake_outer_boolean_serialize(body => $body) +> OuterBoolean fake_outer_boolean_serialize(boolean_post_body => $boolean_post_body) @@ -33,10 +35,10 @@ use WWW::SwaggerClient::FakeApi; my $api_instance = WWW::SwaggerClient::FakeApi->new( ); -my $body = WWW::SwaggerClient::Object::OuterBoolean->new(); # OuterBoolean | Input boolean as post body +my $boolean_post_body = WWW::SwaggerClient::Object::boolean->new(); # boolean | Input boolean as post body eval { - my $result = $api_instance->fake_outer_boolean_serialize(body => $body); + my $result = $api_instance->fake_outer_boolean_serialize(boolean_post_body => $boolean_post_body); print Dumper($result); }; if ($@) { @@ -48,7 +50,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OuterBoolean**](OuterBoolean.md)| Input boolean as post body | [optional] + **boolean_post_body** | **boolean**| Input boolean as post body | [optional] ### Return type @@ -60,13 +62,13 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined + - **Content-Type**: */* + - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **fake_outer_composite_serialize** -> OuterComposite fake_outer_composite_serialize(body => $body) +> OuterComposite fake_outer_composite_serialize(outer_composite => $outer_composite) @@ -79,10 +81,10 @@ use WWW::SwaggerClient::FakeApi; my $api_instance = WWW::SwaggerClient::FakeApi->new( ); -my $body = WWW::SwaggerClient::Object::OuterComposite->new(); # OuterComposite | Input composite as post body +my $outer_composite = WWW::SwaggerClient::Object::OuterComposite->new(); # OuterComposite | Input composite as post body eval { - my $result = $api_instance->fake_outer_composite_serialize(body => $body); + my $result = $api_instance->fake_outer_composite_serialize(outer_composite => $outer_composite); print Dumper($result); }; if ($@) { @@ -94,7 +96,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] + **outer_composite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] ### Return type @@ -106,8 +108,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined + - **Content-Type**: */* + - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -125,7 +127,7 @@ use WWW::SwaggerClient::FakeApi; my $api_instance = WWW::SwaggerClient::FakeApi->new( ); -my $body = WWW::SwaggerClient::Object::OuterNumber->new(); # OuterNumber | Input number as post body +my $body = WWW::SwaggerClient::Object::Number->new(); # Number | Input number as post body eval { my $result = $api_instance->fake_outer_number_serialize(body => $body); @@ -140,7 +142,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OuterNumber**](OuterNumber.md)| Input number as post body | [optional] + **body** | **Number**| Input number as post body | [optional] ### Return type @@ -152,8 +154,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined + - **Content-Type**: */* + - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -171,7 +173,7 @@ use WWW::SwaggerClient::FakeApi; my $api_instance = WWW::SwaggerClient::FakeApi->new( ); -my $body = WWW::SwaggerClient::Object::OuterString->new(); # OuterString | Input string as post body +my $body = WWW::SwaggerClient::Object::string->new(); # string | Input string as post body eval { my $result = $api_instance->fake_outer_string_serialize(body => $body); @@ -186,7 +188,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OuterString**](OuterString.md)| Input string as post body | [optional] + **body** | **string**| Input string as post body | [optional] ### Return type @@ -198,13 +200,58 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined + - **Content-Type**: */* + - **Accept**: */* + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_body_with_query_params** +> test_body_with_query_params(query => $query, user => $user) + + + +### Example +```perl +use Data::Dumper; +use WWW::SwaggerClient::FakeApi; +my $api_instance = WWW::SwaggerClient::FakeApi->new( +); + +my $query = 'query_example'; # string | +my $user = WWW::SwaggerClient::Object::User->new(); # User | + +eval { + $api_instance->test_body_with_query_params(query => $query, user => $user); +}; +if ($@) { + warn "Exception when calling FakeApi->test_body_with_query_params: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **string**| | + **user** | [**User**](User.md)| | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **test_client_model** -> Client test_client_model(body => $body) +> Client test_client_model(client => $client) To test \"client\" model @@ -217,10 +264,10 @@ use WWW::SwaggerClient::FakeApi; my $api_instance = WWW::SwaggerClient::FakeApi->new( ); -my $body = WWW::SwaggerClient::Object::Client->new(); # Client | client model +my $client = WWW::SwaggerClient::Object::Client->new(); # Client | client model eval { - my $result = $api_instance->test_client_model(body => $body); + my $result = $api_instance->test_client_model(client => $client); print Dumper($result); }; if ($@) { @@ -232,7 +279,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | + **client** | [**Client**](Client.md)| client model | ### Return type @@ -267,20 +314,20 @@ my $api_instance = WWW::SwaggerClient::FakeApi->new( password => 'YOUR_PASSWORD', ); -my $number = 3.4; # Number | None -my $double = 1.2; # double | None -my $pattern_without_delimiter = 'pattern_without_delimiter_example'; # string | None -my $byte = 'byte_example'; # string | None -my $integer = 56; # int | None -my $int32 = 56; # int | None -my $int64 = 789; # int | None -my $float = 3.4; # double | None -my $string = 'string_example'; # string | None -my $binary = 'B'; # string | None -my $date = DateTime->from_epoch(epoch => str2time('2013-10-20')); # DateTime | None -my $date_time = DateTime->from_epoch(epoch => str2time('2013-10-20T19:20:30+01:00')); # DateTime | None -my $password = 'password_example'; # string | None -my $callback = 'callback_example'; # string | None +my $number = ; # Number | None +my $double = ; # double | None +my $pattern_without_delimiter = 'null'; # string | None +my $byte = 'null'; # string | None +my $integer = ; # int | None +my $int32 = ; # int | None +my $int64 = ; # int | None +my $float = ; # double | None +my $string = 'null'; # string | None +my $binary = 'null'; # File | None +my $date = DateTime->from_epoch(epoch => str2time('null')); # DateTime | None +my $date_time = DateTime->from_epoch(epoch => str2time('null')); # DateTime | None +my $password = 'null'; # string | None +my $callback = 'null'; # string | None eval { $api_instance->test_endpoint_parameters(number => $number, double => $double, pattern_without_delimiter => $pattern_without_delimiter, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, string => $string, binary => $binary, date => $date, date_time => $date_time, password => $password, callback => $callback); @@ -303,7 +350,7 @@ Name | Type | Description | Notes **int64** | **int**| None | [optional] **float** | **double**| None | [optional] **string** | **string**| None | [optional] - **binary** | **string**| None | [optional] + **binary** | **File****File**| None | [optional] **date** | **DateTime**| None | [optional] **date_time** | **DateTime**| None | [optional] **password** | **string**| None | [optional] @@ -319,13 +366,13 @@ void (empty response body) ### HTTP request headers - - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **test_enum_parameters** -> test_enum_parameters(enum_form_string_array => $enum_form_string_array, enum_form_string => $enum_form_string, enum_header_string_array => $enum_header_string_array, enum_header_string => $enum_header_string, enum_query_string_array => $enum_query_string_array, enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double) +> test_enum_parameters(enum_header_string_array => $enum_header_string_array, enum_header_string => $enum_header_string, enum_query_string_array => $enum_query_string_array, enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double, enum_form_string_array => $enum_form_string_array, enum_form_string => $enum_form_string) To test enum parameters @@ -338,17 +385,17 @@ use WWW::SwaggerClient::FakeApi; my $api_instance = WWW::SwaggerClient::FakeApi->new( ); -my $enum_form_string_array = []; # ARRAY[string] | Form parameter enum test (string array) -my $enum_form_string = 'enum_form_string_example'; # string | Form parameter enum test (string) my $enum_header_string_array = []; # ARRAY[string] | Header parameter enum test (string array) my $enum_header_string = 'enum_header_string_example'; # string | Header parameter enum test (string) my $enum_query_string_array = []; # ARRAY[string] | Query parameter enum test (string array) my $enum_query_string = 'enum_query_string_example'; # string | Query parameter enum test (string) my $enum_query_integer = 56; # int | Query parameter enum test (double) my $enum_query_double = 1.2; # double | Query parameter enum test (double) +my $enum_form_string_array = ; # ARRAY[string] | Form parameter enum test (string array) +my $enum_form_string = 'null'; # string | Form parameter enum test (string) eval { - $api_instance->test_enum_parameters(enum_form_string_array => $enum_form_string_array, enum_form_string => $enum_form_string, enum_header_string_array => $enum_header_string_array, enum_header_string => $enum_header_string, enum_query_string_array => $enum_query_string_array, enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double); + $api_instance->test_enum_parameters(enum_header_string_array => $enum_header_string_array, enum_header_string => $enum_header_string, enum_query_string_array => $enum_query_string_array, enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double, enum_form_string_array => $enum_form_string_array, enum_form_string => $enum_form_string); }; if ($@) { warn "Exception when calling FakeApi->test_enum_parameters: $@\n"; @@ -359,14 +406,14 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **enum_form_string_array** | [**ARRAY[string]**](string.md)| Form parameter enum test (string array) | [optional] - **enum_form_string** | **string**| Form parameter enum test (string) | [optional] [default to -efg] **enum_header_string_array** | [**ARRAY[string]**](string.md)| Header parameter enum test (string array) | [optional] - **enum_header_string** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enum_header_string** | **string**| Header parameter enum test (string) | [optional] **enum_query_string_array** | [**ARRAY[string]**](string.md)| Query parameter enum test (string array) | [optional] - **enum_query_string** | **string**| Query parameter enum test (string) | [optional] [default to -efg] + **enum_query_string** | **string**| Query parameter enum test (string) | [optional] **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] **enum_query_double** | **double**| Query parameter enum test (double) | [optional] + **enum_form_string_array** | [**ARRAY[string]**](ARRAY.md)| Form parameter enum test (string array) | [optional] + **enum_form_string** | **string**| Form parameter enum test (string) | [optional] ### Return type @@ -378,8 +425,51 @@ No authorization required ### HTTP request headers - - **Content-Type**: */* - - **Accept**: */* + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_inline_additional_properties** +> test_inline_additional_properties(body => $body) + +test inline additionalProperties + +### Example +```perl +use Data::Dumper; +use WWW::SwaggerClient::FakeApi; +my $api_instance = WWW::SwaggerClient::FakeApi->new( +); + +my $body = WWW::SwaggerClient::Object::HASH[string,string]->new(); # HASH[string,string] | request body + +eval { + $api_instance->test_inline_additional_properties(body => $body); +}; +if ($@) { + warn "Exception when calling FakeApi->test_inline_additional_properties: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **HASH[string,string]**| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -388,8 +478,6 @@ No authorization required test json serialization of form data - - ### Example ```perl use Data::Dumper; @@ -397,8 +485,8 @@ use WWW::SwaggerClient::FakeApi; my $api_instance = WWW::SwaggerClient::FakeApi->new( ); -my $param = 'param_example'; # string | field1 -my $param2 = 'param2_example'; # string | field2 +my $param = 'null'; # string | field1 +my $param2 = 'null'; # string | field2 eval { $api_instance->test_json_form_data(param => $param, param2 => $param2); @@ -425,7 +513,7 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json + - **Content-Type**: application/x-www-form-urlencoded - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/perl/docs/FakeClassnameTags123Api.md b/samples/client/petstore/perl/docs/FakeClassnameTags123Api.md index ae6da4daf6c5..c4eea8c04598 100644 --- a/samples/client/petstore/perl/docs/FakeClassnameTags123Api.md +++ b/samples/client/petstore/perl/docs/FakeClassnameTags123Api.md @@ -13,7 +13,9 @@ Method | HTTP request | Description # **test_classname** -> Client test_classname(body => $body) +> Client test_classname(client => $client) + +To test class name in snake case To test class name in snake case @@ -29,10 +31,10 @@ my $api_instance = WWW::SwaggerClient::FakeClassnameTags123Api->new( #api_key_prefix => {'api_key_query' => 'Bearer'}, ); -my $body = WWW::SwaggerClient::Object::Client->new(); # Client | client model +my $client = WWW::SwaggerClient::Object::Client->new(); # Client | client model eval { - my $result = $api_instance->test_classname(body => $body); + my $result = $api_instance->test_classname(client => $client); print Dumper($result); }; if ($@) { @@ -44,7 +46,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | + **client** | [**Client**](Client.md)| client model | ### Return type diff --git a/samples/client/petstore/perl/docs/FormatTest.md b/samples/client/petstore/perl/docs/FormatTest.md index 9ba3aeaf17b8..052691569776 100644 --- a/samples/client/petstore/perl/docs/FormatTest.md +++ b/samples/client/petstore/perl/docs/FormatTest.md @@ -16,7 +16,7 @@ Name | Type | Description | Notes **double** | **double** | | [optional] **string** | **string** | | [optional] **byte** | **string** | | -**binary** | **string** | | [optional] +**binary** | [**File**](File.md) | | [optional] **date** | **DateTime** | | **date_time** | **DateTime** | | [optional] **uuid** | [**UUID**](UUID.md) | | [optional] diff --git a/samples/client/petstore/perl/docs/PetApi.md b/samples/client/petstore/perl/docs/PetApi.md index 29e79394055b..c97f85648f4b 100644 --- a/samples/client/petstore/perl/docs/PetApi.md +++ b/samples/client/petstore/perl/docs/PetApi.md @@ -20,12 +20,10 @@ Method | HTTP request | Description # **add_pet** -> add_pet(body => $body) +> add_pet(pet => $pet) Add a new pet to the store - - ### Example ```perl use Data::Dumper; @@ -36,10 +34,10 @@ my $api_instance = WWW::SwaggerClient::PetApi->new( access_token => 'YOUR_ACCESS_TOKEN', ); -my $body = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store +my $pet = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store eval { - $api_instance->add_pet(body => $body); + $api_instance->add_pet(pet => $pet); }; if ($@) { warn "Exception when calling PetApi->add_pet: $@\n"; @@ -50,7 +48,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -63,7 +61,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: application/json, application/xml - - **Accept**: application/xml, application/json + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -72,8 +70,6 @@ void (empty response body) Deletes a pet - - ### Example ```perl use Data::Dumper; @@ -113,7 +109,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -267,12 +263,10 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **update_pet** -> update_pet(body => $body) +> update_pet(pet => $pet) Update an existing pet - - ### Example ```perl use Data::Dumper; @@ -283,10 +277,10 @@ my $api_instance = WWW::SwaggerClient::PetApi->new( access_token => 'YOUR_ACCESS_TOKEN', ); -my $body = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store +my $pet = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store eval { - $api_instance->update_pet(body => $body); + $api_instance->update_pet(pet => $pet); }; if ($@) { warn "Exception when calling PetApi->update_pet: $@\n"; @@ -297,7 +291,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -310,7 +304,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: application/json, application/xml - - **Accept**: application/xml, application/json + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -319,8 +313,6 @@ void (empty response body) Updates a pet in the store with form data - - ### Example ```perl use Data::Dumper; @@ -332,8 +324,8 @@ my $api_instance = WWW::SwaggerClient::PetApi->new( ); my $pet_id = 789; # int | ID of pet that needs to be updated -my $name = 'name_example'; # string | Updated name of the pet -my $status = 'status_example'; # string | Updated status of the pet +my $name = 'null'; # string | Updated name of the pet +my $status = 'null'; # string | Updated status of the pet eval { $api_instance->update_pet_with_form(pet_id => $pet_id, name => $name, status => $status); @@ -362,7 +354,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: application/xml, application/json + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -371,8 +363,6 @@ void (empty response body) uploads an image - - ### Example ```perl use Data::Dumper; @@ -384,8 +374,8 @@ my $api_instance = WWW::SwaggerClient::PetApi->new( ); my $pet_id = 789; # int | ID of pet to update -my $additional_metadata = 'additional_metadata_example'; # string | Additional data to pass to server -my $file = '/path/to/file.txt'; # File | file to upload +my $additional_metadata = 'null'; # string | Additional data to pass to server +my $file = 'null'; # File | file to upload eval { my $result = $api_instance->upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file); @@ -402,7 +392,7 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| ID of pet to update | **additional_metadata** | **string**| Additional data to pass to server | [optional] - **file** | **File**| file to upload | [optional] + **file** | **File****File**| file to upload | [optional] ### Return type diff --git a/samples/client/petstore/perl/docs/SpecialModelName_.md b/samples/client/petstore/perl/docs/SpecialModelName_.md new file mode 100644 index 000000000000..6d66785a4031 --- /dev/null +++ b/samples/client/petstore/perl/docs/SpecialModelName_.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::SpecialModelName_ + +## Load the model package +```perl +use WWW::SwaggerClient::Object::SpecialModelName_; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**__special[property/name]** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/StoreApi.md b/samples/client/petstore/perl/docs/StoreApi.md index ce79bd4ed45e..b72615abf30e 100644 --- a/samples/client/petstore/perl/docs/StoreApi.md +++ b/samples/client/petstore/perl/docs/StoreApi.md @@ -56,7 +56,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -154,12 +154,10 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **place_order** -> Order place_order(body => $body) +> Order place_order(order => $order) Place an order for a pet - - ### Example ```perl use Data::Dumper; @@ -167,10 +165,10 @@ use WWW::SwaggerClient::StoreApi; my $api_instance = WWW::SwaggerClient::StoreApi->new( ); -my $body = WWW::SwaggerClient::Object::Order->new(); # Order | order placed for purchasing the pet +my $order = WWW::SwaggerClient::Object::Order->new(); # Order | order placed for purchasing the pet eval { - my $result = $api_instance->place_order(body => $body); + my $result = $api_instance->place_order(order => $order); print Dumper($result); }; if ($@) { @@ -182,7 +180,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Order**](Order.md)| order placed for purchasing the pet | + **order** | [**Order**](Order.md)| order placed for purchasing the pet | ### Return type @@ -194,7 +192,7 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined + - **Content-Type**: */* - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/perl/docs/UserApi.md b/samples/client/petstore/perl/docs/UserApi.md index 0504988cedce..18f3b394e5d9 100644 --- a/samples/client/petstore/perl/docs/UserApi.md +++ b/samples/client/petstore/perl/docs/UserApi.md @@ -20,7 +20,7 @@ Method | HTTP request | Description # **create_user** -> create_user(body => $body) +> create_user(user => $user) Create user @@ -33,10 +33,10 @@ use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new( ); -my $body = WWW::SwaggerClient::Object::User->new(); # User | Created user object +my $user = WWW::SwaggerClient::Object::User->new(); # User | Created user object eval { - $api_instance->create_user(body => $body); + $api_instance->create_user(user => $user); }; if ($@) { warn "Exception when calling UserApi->create_user: $@\n"; @@ -47,7 +47,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**User**](User.md)| Created user object | + **user** | [**User**](User.md)| Created user object | ### Return type @@ -59,18 +59,16 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: */* + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **create_users_with_array_input** -> create_users_with_array_input(body => $body) +> create_users_with_array_input(user => $user) Creates list of users with given input array - - ### Example ```perl use Data::Dumper; @@ -78,10 +76,10 @@ use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new( ); -my $body = [WWW::SwaggerClient::Object::ARRAY[User]->new()]; # ARRAY[User] | List of user object +my $user = [WWW::SwaggerClient::Object::ARRAY[User]->new()]; # ARRAY[User] | List of user object eval { - $api_instance->create_users_with_array_input(body => $body); + $api_instance->create_users_with_array_input(user => $user); }; if ($@) { warn "Exception when calling UserApi->create_users_with_array_input: $@\n"; @@ -92,7 +90,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**ARRAY[User]**](User.md)| List of user object | + **user** | [**ARRAY[User]**](User.md)| List of user object | ### Return type @@ -104,18 +102,16 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: */* + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **create_users_with_list_input** -> create_users_with_list_input(body => $body) +> create_users_with_list_input(user => $user) Creates list of users with given input array - - ### Example ```perl use Data::Dumper; @@ -123,10 +119,10 @@ use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new( ); -my $body = [WWW::SwaggerClient::Object::ARRAY[User]->new()]; # ARRAY[User] | List of user object +my $user = [WWW::SwaggerClient::Object::ARRAY[User]->new()]; # ARRAY[User] | List of user object eval { - $api_instance->create_users_with_list_input(body => $body); + $api_instance->create_users_with_list_input(user => $user); }; if ($@) { warn "Exception when calling UserApi->create_users_with_list_input: $@\n"; @@ -137,7 +133,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**ARRAY[User]**](User.md)| List of user object | + **user** | [**ARRAY[User]**](User.md)| List of user object | ### Return type @@ -149,8 +145,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: */* + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -195,7 +191,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -204,8 +200,6 @@ No authorization required Get user by user name - - ### Example ```perl use Data::Dumper; @@ -213,7 +207,7 @@ use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new( ); -my $username = 'username_example'; # string | The name that needs to be fetched. Use user1 for testing. +my $username = 'username_example'; # string | The name that needs to be fetched. Use user1 for testing. eval { my $result = $api_instance->get_user_by_name(username => $username); @@ -228,7 +222,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **string**| The name that needs to be fetched. Use user1 for testing. | + **username** | **string**| The name that needs to be fetched. Use user1 for testing. | ### Return type @@ -250,8 +244,6 @@ No authorization required Logs user into the system - - ### Example ```perl use Data::Dumper; @@ -298,8 +290,6 @@ No authorization required Logs out current logged in user session - - ### Example ```perl use Data::Dumper; @@ -330,12 +320,12 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **update_user** -> update_user(username => $username, body => $body) +> update_user(username => $username, user => $user) Updated user @@ -349,10 +339,10 @@ my $api_instance = WWW::SwaggerClient::UserApi->new( ); my $username = 'username_example'; # string | name that need to be deleted -my $body = WWW::SwaggerClient::Object::User->new(); # User | Updated user object +my $user = WWW::SwaggerClient::Object::User->new(); # User | Updated user object eval { - $api_instance->update_user(username => $username, body => $body); + $api_instance->update_user(username => $username, user => $user); }; if ($@) { warn "Exception when calling UserApi->update_user: $@\n"; @@ -364,7 +354,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **string**| name that need to be deleted | - **body** | [**User**](User.md)| Updated user object | + **user** | [**User**](User.md)| Updated user object | ### Return type @@ -376,8 +366,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: */* + - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/perl/git_push.sh b/samples/client/petstore/perl/git_push.sh index ed374619b139..ae01b182ae9e 100644 --- a/samples/client/petstore/perl/git_push.sh +++ b/samples/client/petstore/perl/git_push.sh @@ -36,7 +36,7 @@ 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 crediential in your environment." + 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 diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/AnotherfakeApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/AnotherfakeApi.pm index 7fc43d1c156f..0b434f7323fc 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/AnotherfakeApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/AnotherfakeApi.pm @@ -53,10 +53,10 @@ sub new { # # To test special tags # -# @param Client $body client model (required) +# @param Client $client client model (required) { my $params = { - 'body' => { + 'client' => { data_type => 'Client', description => 'client model', required => '1', @@ -73,9 +73,9 @@ sub new { sub test_special_tags { my ($self, %args) = @_; - # verify the required parameter 'body' is set - unless (exists $args{'body'}) { - croak("Missing the required parameter 'body' when calling test_special_tags"); + # verify the required parameter 'client' is set + unless (exists $args{'client'}) { + croak("Missing the required parameter 'client' when calling test_special_tags"); } # parse inputs @@ -95,8 +95,8 @@ sub test_special_tags { my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'client'}) { + $_body_data = $args{'client'}; } # authentication setting, if any diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm index 8f4b272637ad..9bb9bd94dc81 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm @@ -53,11 +53,11 @@ sub new { # # # -# @param OuterBoolean $body Input boolean as post body (optional) +# @param boolean $boolean_post_body Input boolean as post body (optional) { my $params = { - 'body' => { - data_type => 'OuterBoolean', + 'boolean_post_body' => { + data_type => 'boolean', description => 'Input boolean as post body', required => '0', }, @@ -82,16 +82,16 @@ sub fake_outer_boolean_serialize { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept(); + my $_header_accept = $self->{api_client}->select_header_accept('*/*'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('*/*'); my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'boolean_post_body'}) { + $_body_data = $args{'boolean_post_body'}; } # authentication setting, if any @@ -113,10 +113,10 @@ sub fake_outer_boolean_serialize { # # # -# @param OuterComposite $body Input composite as post body (optional) +# @param OuterComposite $outer_composite Input composite as post body (optional) { my $params = { - 'body' => { + 'outer_composite' => { data_type => 'OuterComposite', description => 'Input composite as post body', required => '0', @@ -142,16 +142,16 @@ sub fake_outer_composite_serialize { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept(); + my $_header_accept = $self->{api_client}->select_header_accept('*/*'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('*/*'); my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'outer_composite'}) { + $_body_data = $args{'outer_composite'}; } # authentication setting, if any @@ -173,11 +173,11 @@ sub fake_outer_composite_serialize { # # # -# @param OuterNumber $body Input number as post body (optional) +# @param Number $body Input number as post body (optional) { my $params = { 'body' => { - data_type => 'OuterNumber', + data_type => 'Number', description => 'Input number as post body', required => '0', }, @@ -202,11 +202,11 @@ sub fake_outer_number_serialize { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept(); + my $_header_accept = $self->{api_client}->select_header_accept('*/*'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('*/*'); my $_body_data; # body params @@ -233,11 +233,11 @@ sub fake_outer_number_serialize { # # # -# @param OuterString $body Input string as post body (optional) +# @param string $body Input string as post body (optional) { my $params = { 'body' => { - data_type => 'OuterString', + data_type => 'string', description => 'Input string as post body', required => '0', }, @@ -262,11 +262,11 @@ sub fake_outer_string_serialize { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept(); + my $_header_accept = $self->{api_client}->select_header_accept('*/*'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('*/*'); my $_body_data; # body params @@ -288,15 +288,92 @@ sub fake_outer_string_serialize { return $_response_object; } +# +# test_body_with_query_params +# +# +# +# @param string $query (required) +# @param User $user (required) +{ + my $params = { + 'query' => { + data_type => 'string', + description => '', + required => '1', + }, + 'user' => { + data_type => 'User', + description => '', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ 'test_body_with_query_params' } = { + summary => '', + params => $params, + returns => undef, + }; +} +# @return void +# +sub test_body_with_query_params { + my ($self, %args) = @_; + + # verify the required parameter 'query' is set + unless (exists $args{'query'}) { + croak("Missing the required parameter 'query' when calling test_body_with_query_params"); + } + + # verify the required parameter 'user' is set + unless (exists $args{'user'}) { + croak("Missing the required parameter 'user' when calling test_body_with_query_params"); + } + + # parse inputs + my $_resource_path = '/fake/body-with-query-params'; + + my $_method = 'PUT'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept(); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); + + # query params + if ( exists $args{'query'}) { + $query_params->{'query'} = $self->{api_client}->to_query_value($args{'query'}); + } + + my $_body_data; + # body params + if ( exists $args{'user'}) { + $_body_data = $args{'user'}; + } + + # authentication setting, if any + my $auth_settings = [qw()]; + + # make the API Call + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; +} + # # test_client_model # # To test \"client\" model # -# @param Client $body client model (required) +# @param Client $client client model (required) { my $params = { - 'body' => { + 'client' => { data_type => 'Client', description => 'client model', required => '1', @@ -313,9 +390,9 @@ sub fake_outer_string_serialize { sub test_client_model { my ($self, %args) = @_; - # verify the required parameter 'body' is set - unless (exists $args{'body'}) { - croak("Missing the required parameter 'body' when calling test_client_model"); + # verify the required parameter 'client' is set + unless (exists $args{'client'}) { + croak("Missing the required parameter 'client' when calling test_client_model"); } # parse inputs @@ -335,8 +412,8 @@ sub test_client_model { my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'client'}) { + $_body_data = $args{'client'}; } # authentication setting, if any @@ -367,7 +444,7 @@ sub test_client_model { # @param int $int64 None (optional) # @param double $float None (optional) # @param string $string None (optional) -# @param string $binary None (optional) +# @param File $binary None (optional) # @param DateTime $date None (optional) # @param DateTime $date_time None (optional) # @param string $password None (optional) @@ -420,7 +497,7 @@ sub test_client_model { required => '0', }, 'binary' => { - data_type => 'string', + data_type => 'File', description => 'None', required => '0', }, @@ -485,11 +562,11 @@ sub test_endpoint_parameters { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml; charset=utf-8', 'application/json; charset=utf-8'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/xml; charset=utf-8', 'application/json; charset=utf-8'); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/x-www-form-urlencoded'); # form params if ( exists $args{'integer'} ) { @@ -538,8 +615,9 @@ sub test_endpoint_parameters { # form params if ( exists $args{'binary'} ) { - $form_params->{'binary'} = $self->{api_client}->to_form_value($args{'binary'}); - } + $form_params->{'binary'} = [] unless defined $form_params->{'binary'}; + push @{$form_params->{'binary'}}, $args{'binary'}; + } # form params if ( exists $args{'date'} ) { @@ -577,26 +655,16 @@ sub test_endpoint_parameters { # # To test enum parameters # -# @param ARRAY[string] $enum_form_string_array Form parameter enum test (string array) (optional) -# @param string $enum_form_string Form parameter enum test (string) (optional, default to -efg) # @param ARRAY[string] $enum_header_string_array Header parameter enum test (string array) (optional) -# @param string $enum_header_string Header parameter enum test (string) (optional, default to -efg) +# @param string $enum_header_string Header parameter enum test (string) (optional) # @param ARRAY[string] $enum_query_string_array Query parameter enum test (string array) (optional) -# @param string $enum_query_string Query parameter enum test (string) (optional, default to -efg) +# @param string $enum_query_string Query parameter enum test (string) (optional) # @param int $enum_query_integer Query parameter enum test (double) (optional) # @param double $enum_query_double Query parameter enum test (double) (optional) +# @param ARRAY[string] $enum_form_string_array Form parameter enum test (string array) (optional) +# @param string $enum_form_string Form parameter enum test (string) (optional) { my $params = { - 'enum_form_string_array' => { - data_type => 'ARRAY[string]', - description => 'Form parameter enum test (string array)', - required => '0', - }, - 'enum_form_string' => { - data_type => 'string', - description => 'Form parameter enum test (string)', - required => '0', - }, 'enum_header_string_array' => { data_type => 'ARRAY[string]', description => 'Header parameter enum test (string array)', @@ -627,6 +695,16 @@ sub test_endpoint_parameters { description => 'Query parameter enum test (double)', required => '0', }, + 'enum_form_string_array' => { + data_type => 'ARRAY[string]', + description => 'Form parameter enum test (string array)', + required => '0', + }, + 'enum_form_string' => { + data_type => 'string', + description => 'Form parameter enum test (string)', + required => '0', + }, }; __PACKAGE__->method_documentation->{ 'test_enum_parameters' } = { summary => 'To test enum parameters', @@ -648,11 +726,11 @@ sub test_enum_parameters { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('*/*'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('*/*'); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/x-www-form-urlencoded'); # query params if ( exists $args{'enum_query_string_array'}) { @@ -669,6 +747,11 @@ sub test_enum_parameters { $query_params->{'enum_query_integer'} = $self->{api_client}->to_query_value($args{'enum_query_integer'}); } + # query params + if ( exists $args{'enum_query_double'}) { + $query_params->{'enum_query_double'} = $self->{api_client}->to_query_value($args{'enum_query_double'}); + } + # header params if ( exists $args{'enum_header_string_array'}) { $header_params->{'enum_header_string_array'} = $self->{api_client}->to_header_value($args{'enum_header_string_array'}); @@ -689,12 +772,68 @@ sub test_enum_parameters { $form_params->{'enum_form_string'} = $self->{api_client}->to_form_value($args{'enum_form_string'}); } - # form params - if ( exists $args{'enum_query_double'} ) { - $form_params->{'enum_query_double'} = $self->{api_client}->to_form_value($args{'enum_query_double'}); + my $_body_data; + # authentication setting, if any + my $auth_settings = [qw()]; + + # make the API Call + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; +} + +# +# test_inline_additional_properties +# +# test inline additionalProperties +# +# @param HASH[string,string] $body request body (required) +{ + my $params = { + 'body' => { + data_type => 'HASH[string,string]', + description => 'request body', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ 'test_inline_additional_properties' } = { + summary => 'test inline additionalProperties', + params => $params, + returns => undef, + }; +} +# @return void +# +sub test_inline_additional_properties { + my ($self, %args) = @_; + + # verify the required parameter 'body' is set + unless (exists $args{'body'}) { + croak("Missing the required parameter 'body' when calling test_inline_additional_properties"); } - + + # parse inputs + my $_resource_path = '/fake/inline-additionalProperties'; + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept(); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); + my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + # authentication setting, if any my $auth_settings = [qw()]; @@ -759,7 +898,7 @@ sub test_json_form_data { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/x-www-form-urlencoded'); # form params if ( exists $args{'param'} ) { diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeClassnameTags123Api.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeClassnameTags123Api.pm index 69d8cc6defce..550387972db9 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeClassnameTags123Api.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeClassnameTags123Api.pm @@ -53,10 +53,10 @@ sub new { # # To test class name in snake case # -# @param Client $body client model (required) +# @param Client $client client model (required) { my $params = { - 'body' => { + 'client' => { data_type => 'Client', description => 'client model', required => '1', @@ -73,9 +73,9 @@ sub new { sub test_classname { my ($self, %args) = @_; - # verify the required parameter 'body' is set - unless (exists $args{'body'}) { - croak("Missing the required parameter 'body' when calling test_classname"); + # verify the required parameter 'client' is set + unless (exists $args{'client'}) { + croak("Missing the required parameter 'client' when calling test_classname"); } # parse inputs @@ -95,8 +95,8 @@ sub test_classname { my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'client'}) { + $_body_data = $args{'client'}; } # authentication setting, if any diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Body4.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Body4.pm new file mode 100644 index 000000000000..9b4e00c3a18a --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Body4.pm @@ -0,0 +1,175 @@ +=begin comment + +Swagger 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 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::Body4; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger 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 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'Body4', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'param' => { + datatype => 'string', + base_name => 'param', + description => 'field1', + format => '', + read_only => '', + }, + 'param2' => { + datatype => 'string', + base_name => 'param2', + description => 'field2', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'param' => 'string', + 'param2' => 'string' +} ); + +__PACKAGE__->attribute_map( { + 'param' => 'param', + 'param2' => 'param2' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm index 0d94500ec78d..5a8e66467758 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm @@ -151,6 +151,13 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'enum_string_required' => { + datatype => 'string', + base_name => 'enum_string_required', + description => '', + format => '', + read_only => '', + }, 'enum_integer' => { datatype => 'int', base_name => 'enum_integer', @@ -176,6 +183,7 @@ __PACKAGE__->method_documentation({ __PACKAGE__->swagger_types( { 'enum_string' => 'string', + 'enum_string_required' => 'string', 'enum_integer' => 'int', 'enum_number' => 'double', 'outer_enum' => 'OuterEnum' @@ -183,6 +191,7 @@ __PACKAGE__->swagger_types( { __PACKAGE__->attribute_map( { 'enum_string' => 'enum_string', + 'enum_string_required' => 'enum_string_required', 'enum_integer' => 'enum_integer', 'enum_number' => 'enum_number', 'outer_enum' => 'outerEnum' diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/FormatTest.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/FormatTest.pm index acbeb44796fd..fb3a61404c00 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/FormatTest.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/FormatTest.pm @@ -30,6 +30,7 @@ use Log::Any qw($log); use Date::Parse; use DateTime; +use WWW::SwaggerClient::Object::File; use WWW::SwaggerClient::Object::Number; use WWW::SwaggerClient::Object::UUID; @@ -202,7 +203,7 @@ __PACKAGE__->method_documentation({ read_only => '', }, 'binary' => { - datatype => 'string', + datatype => 'File', base_name => 'binary', description => '', format => '', @@ -247,7 +248,7 @@ __PACKAGE__->swagger_types( { 'double' => 'double', 'string' => 'string', 'byte' => 'string', - 'binary' => 'string', + 'binary' => 'File', 'date' => 'DateTime', 'date_time' => 'DateTime', 'uuid' => 'UUID', diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/SpecialModelName_.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/SpecialModelName_.pm new file mode 100644 index 000000000000..9c47fb1011d9 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/SpecialModelName_.pm @@ -0,0 +1,166 @@ +=begin comment + +Swagger 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 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::SpecialModelName_; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger 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 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'SpecialModelName_', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + '__special[property/name]' => { + datatype => 'int', + base_name => '$special[property.name]', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + '__special[property/name]' => 'int' +} ); + +__PACKAGE__->attribute_map( { + '__special[property/name]' => '$special[property.name]' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 1511dc4e0c26..8143e862ed5c 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -53,10 +53,10 @@ sub new { # # Add a new pet to the store # -# @param Pet $body Pet object that needs to be added to the store (required) +# @param Pet $pet Pet object that needs to be added to the store (required) { my $params = { - 'body' => { + 'pet' => { data_type => 'Pet', description => 'Pet object that needs to be added to the store', required => '1', @@ -73,9 +73,9 @@ sub new { sub add_pet { my ($self, %args) = @_; - # verify the required parameter 'body' is set - unless (exists $args{'body'}) { - croak("Missing the required parameter 'body' when calling add_pet"); + # verify the required parameter 'pet' is set + unless (exists $args{'pet'}) { + croak("Missing the required parameter 'pet' when calling add_pet"); } # parse inputs @@ -87,7 +87,7 @@ sub add_pet { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml', 'application/json'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } @@ -95,8 +95,8 @@ sub add_pet { my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'pet'}) { + $_body_data = $args{'pet'}; } # authentication setting, if any @@ -154,7 +154,7 @@ sub delete_pet { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml', 'application/json'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } @@ -385,10 +385,10 @@ sub get_pet_by_id { # # Update an existing pet # -# @param Pet $body Pet object that needs to be added to the store (required) +# @param Pet $pet Pet object that needs to be added to the store (required) { my $params = { - 'body' => { + 'pet' => { data_type => 'Pet', description => 'Pet object that needs to be added to the store', required => '1', @@ -405,9 +405,9 @@ sub get_pet_by_id { sub update_pet { my ($self, %args) = @_; - # verify the required parameter 'body' is set - unless (exists $args{'body'}) { - croak("Missing the required parameter 'body' when calling update_pet"); + # verify the required parameter 'pet' is set + unless (exists $args{'pet'}) { + croak("Missing the required parameter 'pet' when calling update_pet"); } # parse inputs @@ -419,7 +419,7 @@ sub update_pet { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml', 'application/json'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } @@ -427,8 +427,8 @@ sub update_pet { my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'pet'}) { + $_body_data = $args{'pet'}; } # authentication setting, if any @@ -492,7 +492,7 @@ sub update_pet_with_form { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml', 'application/json'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm index 0c9234706e05..f23f6f2a270a 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm @@ -56,7 +56,7 @@ has version_info => ( is => 'ro', default => sub { { app_name => 'Swagger Petstore', app_version => '1.0.0', - generator_class => 'io.swagger.codegen.languages.PerlClientCodegen', + generator_class => 'org.openapitools.codegen.languages.PerlClientCodegen', } }, documentation => 'Information about the application version and the codegen codebase version' ); @@ -120,7 +120,7 @@ WWW::SwaggerClient::Role - a Moose role for the Swagger Petstore Automatically generated by the Perl Swagger Codegen project: =over 4 -=item Build package: io.swagger.codegen.languages.PerlClientCodegen +=item Build package: org.openapitools.codegen.languages.PerlClientCodegen =item Codegen version: diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index 21354ad229e0..4bacd73c241f 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -87,7 +87,7 @@ sub delete_order { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml', 'application/json'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } @@ -232,10 +232,10 @@ sub get_order_by_id { # # Place an order for a pet # -# @param Order $body order placed for purchasing the pet (required) +# @param Order $order order placed for purchasing the pet (required) { my $params = { - 'body' => { + 'order' => { data_type => 'Order', description => 'order placed for purchasing the pet', required => '1', @@ -252,9 +252,9 @@ sub get_order_by_id { sub place_order { my ($self, %args) = @_; - # verify the required parameter 'body' is set - unless (exists $args{'body'}) { - croak("Missing the required parameter 'body' when calling place_order"); + # verify the required parameter 'order' is set + unless (exists $args{'order'}) { + croak("Missing the required parameter 'order' when calling place_order"); } # parse inputs @@ -270,12 +270,12 @@ sub place_order { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('*/*'); my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'order'}) { + $_body_data = $args{'order'}; } # authentication setting, if any diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index 025d07c211f7..06302dd4d10b 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -53,10 +53,10 @@ sub new { # # Create user # -# @param User $body Created user object (required) +# @param User $user Created user object (required) { my $params = { - 'body' => { + 'user' => { data_type => 'User', description => 'Created user object', required => '1', @@ -73,9 +73,9 @@ sub new { sub create_user { my ($self, %args) = @_; - # verify the required parameter 'body' is set - unless (exists $args{'body'}) { - croak("Missing the required parameter 'body' when calling create_user"); + # verify the required parameter 'user' is set + unless (exists $args{'user'}) { + croak("Missing the required parameter 'user' when calling create_user"); } # parse inputs @@ -87,16 +87,16 @@ sub create_user { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml', 'application/json'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('*/*'); my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'user'}) { + $_body_data = $args{'user'}; } # authentication setting, if any @@ -114,10 +114,10 @@ sub create_user { # # Creates list of users with given input array # -# @param ARRAY[User] $body List of user object (required) +# @param ARRAY[User] $user List of user object (required) { my $params = { - 'body' => { + 'user' => { data_type => 'ARRAY[User]', description => 'List of user object', required => '1', @@ -134,9 +134,9 @@ sub create_user { sub create_users_with_array_input { my ($self, %args) = @_; - # verify the required parameter 'body' is set - unless (exists $args{'body'}) { - croak("Missing the required parameter 'body' when calling create_users_with_array_input"); + # verify the required parameter 'user' is set + unless (exists $args{'user'}) { + croak("Missing the required parameter 'user' when calling create_users_with_array_input"); } # parse inputs @@ -148,16 +148,16 @@ sub create_users_with_array_input { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml', 'application/json'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('*/*'); my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'user'}) { + $_body_data = $args{'user'}; } # authentication setting, if any @@ -175,10 +175,10 @@ sub create_users_with_array_input { # # Creates list of users with given input array # -# @param ARRAY[User] $body List of user object (required) +# @param ARRAY[User] $user List of user object (required) { my $params = { - 'body' => { + 'user' => { data_type => 'ARRAY[User]', description => 'List of user object', required => '1', @@ -195,9 +195,9 @@ sub create_users_with_array_input { sub create_users_with_list_input { my ($self, %args) = @_; - # verify the required parameter 'body' is set - unless (exists $args{'body'}) { - croak("Missing the required parameter 'body' when calling create_users_with_list_input"); + # verify the required parameter 'user' is set + unless (exists $args{'user'}) { + croak("Missing the required parameter 'user' when calling create_users_with_list_input"); } # parse inputs @@ -209,16 +209,16 @@ sub create_users_with_list_input { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml', 'application/json'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('*/*'); my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'user'}) { + $_body_data = $args{'user'}; } # authentication setting, if any @@ -270,7 +270,7 @@ sub delete_user { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml', 'application/json'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } @@ -299,12 +299,12 @@ sub delete_user { # # Get user by user name # -# @param string $username The name that needs to be fetched. Use user1 for testing. (required) +# @param string $username The name that needs to be fetched. Use user1 for testing. (required) { my $params = { 'username' => { data_type => 'string', - description => 'The name that needs to be fetched. Use user1 for testing. ', + description => 'The name that needs to be fetched. Use user1 for testing.', required => '1', }, }; @@ -470,7 +470,7 @@ sub logout_user { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml', 'application/json'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } @@ -493,7 +493,7 @@ sub logout_user { # Updated user # # @param string $username name that need to be deleted (required) -# @param User $body Updated user object (required) +# @param User $user Updated user object (required) { my $params = { 'username' => { @@ -501,7 +501,7 @@ sub logout_user { description => 'name that need to be deleted', required => '1', }, - 'body' => { + 'user' => { data_type => 'User', description => 'Updated user object', required => '1', @@ -523,9 +523,9 @@ sub update_user { croak("Missing the required parameter 'username' when calling update_user"); } - # verify the required parameter 'body' is set - unless (exists $args{'body'}) { - croak("Missing the required parameter 'body' when calling update_user"); + # verify the required parameter 'user' is set + unless (exists $args{'user'}) { + croak("Missing the required parameter 'user' when calling update_user"); } # parse inputs @@ -537,11 +537,11 @@ sub update_user { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/xml', 'application/json'); + my $_header_accept = $self->{api_client}->select_header_accept(); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('*/*'); # path params if ( exists $args{'username'}) { @@ -552,8 +552,8 @@ sub update_user { my $_body_data; # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; + if ( exists $args{'user'}) { + $_body_data = $args{'user'}; } # authentication setting, if any diff --git a/samples/client/petstore/perl/t/Body4Test.t b/samples/client/petstore/perl/t/Body4Test.t new file mode 100644 index 000000000000..f00adf8ce34f --- /dev/null +++ b/samples/client/petstore/perl/t/Body4Test.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger 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 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::Body4'); + +my $instance = WWW::SwaggerClient::Object::Body4->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::Body4'); + diff --git a/samples/client/petstore/perl/t/SpecialModelName_Test.t b/samples/client/petstore/perl/t/SpecialModelName_Test.t new file mode 100644 index 000000000000..69c9089538c0 --- /dev/null +++ b/samples/client/petstore/perl/t/SpecialModelName_Test.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger 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 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::SpecialModelName_'); + +my $instance = WWW::SwaggerClient::Object::SpecialModelName_->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::SpecialModelName_'); + diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 112c5b8ab085..2fd020297c7d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -80,6 +80,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AnotherFakeApi* | [**testSpecialTags**](docs/Api/AnotherFakeApi.md#testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*DefaultApi* | [**testBodyWithQueryParams**](docs/Api/DefaultApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**fakeOuterBooleanSerialize**](docs/Api/FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | *FakeApi* | [**fakeOuterCompositeSerialize**](docs/Api/FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | *FakeApi* | [**fakeOuterNumberSerialize**](docs/Api/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/DefaultApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/DefaultApi.md new file mode 100644 index 000000000000..0185322ccf2c --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/DefaultApi.md @@ -0,0 +1,57 @@ +# Swagger\Client\DefaultApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testBodyWithQueryParams**](DefaultApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | + + +# **testBodyWithQueryParams** +> testBodyWithQueryParams($body, $query) + + + +### Example +```php +testBodyWithQueryParams($body, $query); +} catch (Exception $e) { + echo 'Exception when calling DefaultApi->testBodyWithQueryParams: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**\Swagger\Client\Model\User**](../Model/User.md)| | + **query** | **string**| | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/DefaultApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/DefaultApi.php new file mode 100644 index 000000000000..a24fd708e397 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/DefaultApi.php @@ -0,0 +1,339 @@ +client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation testBodyWithQueryParams + * + * @param \Swagger\Client\Model\User $body body (required) + * @param string $query query (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function testBodyWithQueryParams($body, $query) + { + $this->testBodyWithQueryParamsWithHttpInfo($body, $query); + } + + /** + * Operation testBodyWithQueryParamsWithHttpInfo + * + * @param \Swagger\Client\Model\User $body (required) + * @param string $query (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function testBodyWithQueryParamsWithHttpInfo($body, $query) + { + $returnType = ''; + $request = $this->testBodyWithQueryParamsRequest($body, $query); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation testBodyWithQueryParamsAsync + * + * + * + * @param \Swagger\Client\Model\User $body (required) + * @param string $query (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testBodyWithQueryParamsAsync($body, $query) + { + return $this->testBodyWithQueryParamsAsyncWithHttpInfo($body, $query) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testBodyWithQueryParamsAsyncWithHttpInfo + * + * + * + * @param \Swagger\Client\Model\User $body (required) + * @param string $query (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testBodyWithQueryParamsAsyncWithHttpInfo($body, $query) + { + $returnType = ''; + $request = $this->testBodyWithQueryParamsRequest($body, $query); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testBodyWithQueryParams' + * + * @param \Swagger\Client\Model\User $body (required) + * @param string $query (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function testBodyWithQueryParamsRequest($body, $query) + { + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling testBodyWithQueryParams' + ); + } + // verify the required parameter 'query' is set + if ($query === null || (is_array($query) && count($query) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $query when calling testBodyWithQueryParams' + ); + } + + $resourcePath = '/fake/body-with-query-params'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + if ($query !== null) { + $queryParams['query'] = ObjectSerializer::toQueryValue($query); + } + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'PUT', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php index 6720f6bb8c52..667106ab45f5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php @@ -226,7 +226,7 @@ public function listInvalidProperties() $invalidProperties = []; $allowedValues = $this->getJustSymbolAllowableValues(); - if (!is_null($this->container['just_symbol']) && !in_array($this->container['just_symbol'], $allowedValues)) { + if (!is_null($this->container['just_symbol']) && !in_array($this->container['just_symbol'], $allowedValues, true)) { $invalidProperties[] = sprintf( "invalid value for 'just_symbol', must be one of '%s'", implode("', '", $allowedValues) @@ -246,7 +246,7 @@ public function valid() { $allowedValues = $this->getJustSymbolAllowableValues(); - if (!is_null($this->container['just_symbol']) && !in_array($this->container['just_symbol'], $allowedValues)) { + if (!is_null($this->container['just_symbol']) && !in_array($this->container['just_symbol'], $allowedValues, true)) { return false; } return true; @@ -273,7 +273,7 @@ public function getJustSymbol() public function setJustSymbol($just_symbol) { $allowedValues = $this->getJustSymbolAllowableValues(); - if (!is_null($just_symbol) && !in_array($just_symbol, $allowedValues)) { + if (!is_null($just_symbol) && !in_array($just_symbol, $allowedValues, true)) { throw new \InvalidArgumentException( sprintf( "Invalid value for 'just_symbol', must be one of '%s'", diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index 5c097931fd69..e63084d94a10 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -278,7 +278,7 @@ public function listInvalidProperties() $invalidProperties = []; $allowedValues = $this->getEnumStringAllowableValues(); - if (!is_null($this->container['enum_string']) && !in_array($this->container['enum_string'], $allowedValues)) { + if (!is_null($this->container['enum_string']) && !in_array($this->container['enum_string'], $allowedValues, true)) { $invalidProperties[] = sprintf( "invalid value for 'enum_string', must be one of '%s'", implode("', '", $allowedValues) @@ -289,7 +289,7 @@ public function listInvalidProperties() $invalidProperties[] = "'enum_string_required' can't be null"; } $allowedValues = $this->getEnumStringRequiredAllowableValues(); - if (!is_null($this->container['enum_string_required']) && !in_array($this->container['enum_string_required'], $allowedValues)) { + if (!is_null($this->container['enum_string_required']) && !in_array($this->container['enum_string_required'], $allowedValues, true)) { $invalidProperties[] = sprintf( "invalid value for 'enum_string_required', must be one of '%s'", implode("', '", $allowedValues) @@ -297,7 +297,7 @@ public function listInvalidProperties() } $allowedValues = $this->getEnumIntegerAllowableValues(); - if (!is_null($this->container['enum_integer']) && !in_array($this->container['enum_integer'], $allowedValues)) { + if (!is_null($this->container['enum_integer']) && !in_array($this->container['enum_integer'], $allowedValues, true)) { $invalidProperties[] = sprintf( "invalid value for 'enum_integer', must be one of '%s'", implode("', '", $allowedValues) @@ -305,7 +305,7 @@ public function listInvalidProperties() } $allowedValues = $this->getEnumNumberAllowableValues(); - if (!is_null($this->container['enum_number']) && !in_array($this->container['enum_number'], $allowedValues)) { + if (!is_null($this->container['enum_number']) && !in_array($this->container['enum_number'], $allowedValues, true)) { $invalidProperties[] = sprintf( "invalid value for 'enum_number', must be one of '%s'", implode("', '", $allowedValues) @@ -325,22 +325,22 @@ public function valid() { $allowedValues = $this->getEnumStringAllowableValues(); - if (!is_null($this->container['enum_string']) && !in_array($this->container['enum_string'], $allowedValues)) { + if (!is_null($this->container['enum_string']) && !in_array($this->container['enum_string'], $allowedValues, true)) { return false; } if ($this->container['enum_string_required'] === null) { return false; } $allowedValues = $this->getEnumStringRequiredAllowableValues(); - if (!is_null($this->container['enum_string_required']) && !in_array($this->container['enum_string_required'], $allowedValues)) { + if (!is_null($this->container['enum_string_required']) && !in_array($this->container['enum_string_required'], $allowedValues, true)) { return false; } $allowedValues = $this->getEnumIntegerAllowableValues(); - if (!is_null($this->container['enum_integer']) && !in_array($this->container['enum_integer'], $allowedValues)) { + if (!is_null($this->container['enum_integer']) && !in_array($this->container['enum_integer'], $allowedValues, true)) { return false; } $allowedValues = $this->getEnumNumberAllowableValues(); - if (!is_null($this->container['enum_number']) && !in_array($this->container['enum_number'], $allowedValues)) { + if (!is_null($this->container['enum_number']) && !in_array($this->container['enum_number'], $allowedValues, true)) { return false; } return true; @@ -367,7 +367,7 @@ public function getEnumString() public function setEnumString($enum_string) { $allowedValues = $this->getEnumStringAllowableValues(); - if (!is_null($enum_string) && !in_array($enum_string, $allowedValues)) { + if (!is_null($enum_string) && !in_array($enum_string, $allowedValues, true)) { throw new \InvalidArgumentException( sprintf( "Invalid value for 'enum_string', must be one of '%s'", @@ -400,7 +400,7 @@ public function getEnumStringRequired() public function setEnumStringRequired($enum_string_required) { $allowedValues = $this->getEnumStringRequiredAllowableValues(); - if (!in_array($enum_string_required, $allowedValues)) { + if (!in_array($enum_string_required, $allowedValues, true)) { throw new \InvalidArgumentException( sprintf( "Invalid value for 'enum_string_required', must be one of '%s'", @@ -433,7 +433,7 @@ public function getEnumInteger() public function setEnumInteger($enum_integer) { $allowedValues = $this->getEnumIntegerAllowableValues(); - if (!is_null($enum_integer) && !in_array($enum_integer, $allowedValues)) { + if (!is_null($enum_integer) && !in_array($enum_integer, $allowedValues, true)) { throw new \InvalidArgumentException( sprintf( "Invalid value for 'enum_integer', must be one of '%s'", @@ -466,7 +466,7 @@ public function getEnumNumber() public function setEnumNumber($enum_number) { $allowedValues = $this->getEnumNumberAllowableValues(); - if (!is_null($enum_number) && !in_array($enum_number, $allowedValues)) { + if (!is_null($enum_number) && !in_array($enum_number, $allowedValues, true)) { throw new \InvalidArgumentException( sprintf( "Invalid value for 'enum_number', must be one of '%s'", diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index a8c74e7b7617..8e9d1e45237f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -321,11 +321,11 @@ public function listInvalidProperties() if ($this->container['password'] === null) { $invalidProperties[] = "'password' can't be null"; } - if ((strlen($this->container['password']) > 64)) { + if ((mb_strlen($this->container['password']) > 64)) { $invalidProperties[] = "invalid value for 'password', the character length must be smaller than or equal to 64."; } - if ((strlen($this->container['password']) < 10)) { + if ((mb_strlen($this->container['password']) < 10)) { $invalidProperties[] = "invalid value for 'password', the character length must be bigger than or equal to 10."; } @@ -389,10 +389,10 @@ public function valid() if ($this->container['password'] === null) { return false; } - if (strlen($this->container['password']) > 64) { + if (mb_strlen($this->container['password']) > 64) { return false; } - if (strlen($this->container['password']) < 10) { + if (mb_strlen($this->container['password']) < 10) { return false; } return true; @@ -756,10 +756,10 @@ public function getPassword() */ public function setPassword($password) { - if ((strlen($password) > 64)) { + if ((mb_strlen($password) > 64)) { throw new \InvalidArgumentException('invalid length for $password when calling FormatTest., must be smaller than or equal to 64.'); } - if ((strlen($password) < 10)) { + if ((mb_strlen($password) < 10)) { throw new \InvalidArgumentException('invalid length for $password when calling FormatTest., must be bigger than or equal to 10.'); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 0089f45bcf74..5d6bd5f222b4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -237,7 +237,7 @@ public function listInvalidProperties() $invalidProperties = []; $allowedValues = $this->getStatusAllowableValues(); - if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues)) { + if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { $invalidProperties[] = sprintf( "invalid value for 'status', must be one of '%s'", implode("', '", $allowedValues) @@ -257,7 +257,7 @@ public function valid() { $allowedValues = $this->getStatusAllowableValues(); - if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues)) { + if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { return false; } return true; @@ -380,7 +380,7 @@ public function getStatus() public function setStatus($status) { $allowedValues = $this->getStatusAllowableValues(); - if (!is_null($status) && !in_array($status, $allowedValues)) { + if (!is_null($status) && !in_array($status, $allowedValues, true)) { throw new \InvalidArgumentException( sprintf( "Invalid value for 'status', must be one of '%s'", diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 73e73c892fcb..8c78b7a553e9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -243,7 +243,7 @@ public function listInvalidProperties() $invalidProperties[] = "'photo_urls' can't be null"; } $allowedValues = $this->getStatusAllowableValues(); - if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues)) { + if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { $invalidProperties[] = sprintf( "invalid value for 'status', must be one of '%s'", implode("', '", $allowedValues) @@ -269,7 +269,7 @@ public function valid() return false; } $allowedValues = $this->getStatusAllowableValues(); - if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues)) { + if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { return false; } return true; @@ -416,7 +416,7 @@ public function getStatus() public function setStatus($status) { $allowedValues = $this->getStatusAllowableValues(); - if (!is_null($status) && !in_array($status, $allowedValues)) { + if (!is_null($status) && !in_array($status, $allowedValues, true)) { throw new \InvalidArgumentException( sprintf( "Invalid value for 'status', must be one of '%s'", diff --git a/samples/client/petstore/php/SwaggerClient-php/phpunit.xml.dist b/samples/client/petstore/php/SwaggerClient-php/phpunit.xml.dist index cadedbc24690..c12ee1484773 100644 --- a/samples/client/petstore/php/SwaggerClient-php/phpunit.xml.dist +++ b/samples/client/petstore/php/SwaggerClient-php/phpunit.xml.dist @@ -14,8 +14,8 @@ - ./lib\Api - ./lib\Model + ./lib/Api + ./lib/Model diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/DefaultApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/DefaultApiTest.php new file mode 100644 index 000000000000..f5d11998adff --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/DefaultApiTest.php @@ -0,0 +1,83 @@ +assertSame(EnumTest::ENUM_NUMBER_MINUS_1_DOT_2, -1.2); } + public function testStrictValidation() + { + $enum = new EnumTest([ + 'enum_string' => 0, + ]); + + $this->assertFalse($enum->valid()); + + $expected = [ + "invalid value for 'enum_string', must be one of 'UPPER', 'lower', ''", + "'enum_string_required' can't be null", + ]; + $this->assertSame($expected, $enum->listInvalidProperties()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testThrowExceptionWhenInvalidAmbiguousValueHasPassed() + { + $enum = new EnumTest(); + $enum->setEnumString(0); + } + public function testNonRequiredPropertyIsOptional() { $enum = new EnumTest([ diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/FormatTestTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/FormatTestTest.php new file mode 100644 index 000000000000..e91222a1686d --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/FormatTestTest.php @@ -0,0 +1,26 @@ + $the64MultiByteStrings, + // mandatory parameters + 'number' => 500, + 'byte' => base64_encode('test'), + 'date' => new DateTime(), + ]); + + $this->assertEmpty($formatTest->listInvalidProperties()); + + // Pass the strings via setter. + // Throws InvalidArgumentException if it doesn't count the length correctly. + $formatTest->setPassword($the64MultiByteStrings); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 1cfad6aaeae5..be834d9dda6a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -127,20 +127,6 @@ public function testFindPetByStatus() $this->assertCount(0, $response); } - public function testFindPetsByTags() - { - $response = $this->api->findPetsByTags('test php tag'); - $this->assertGreaterThan(0, count($response)); // at least one object returned - $this->assertSame(get_class($response[0]), Pet::class); // verify the object is Pet - - foreach ($response as $pet) { - $this->assertSame($pet['tags'][0]['name'], 'test php tag'); - } - - $response = $this->api->findPetsByTags('unknown_and_incorrect_tag'); - $this->assertCount(0, $response); - } - public function testUpdatePet() { $petId = 10001; diff --git a/samples/client/petstore/powershell/.swagger-codegen/VERSION b/samples/client/petstore/powershell/.swagger-codegen/VERSION index 7fea99011a6f..096bf47efe31 100644 --- a/samples/client/petstore/powershell/.swagger-codegen/VERSION +++ b/samples/client/petstore/powershell/.swagger-codegen/VERSION @@ -1 +1 @@ -2.2.3-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/powershell/README.md b/samples/client/petstore/powershell/README.md index eed576430453..bd445f2e6747 100644 --- a/samples/client/petstore/powershell/README.md +++ b/samples/client/petstore/powershell/README.md @@ -6,8 +6,8 @@ This PowerShell module is automatically generated by the [Swagger Codegen](https - API version: 1.0.0 - SDK version: -- Build date: 2017-06-20T22:49:00.415+08:00 -- Build package: io.swagger.codegen.languages.PowerShellClientCodegen +- Build date: 2018-04-12T00:40:01.530+08:00 +- Build package: org.openapitools.codegen.languages.PowerShellClientCodegen ## Frameworks supported diff --git a/samples/client/petstore/powershell/src/IO.Swagger/API/PetApi.ps1 b/samples/client/petstore/powershell/src/IO.Swagger/API/PetApi.ps1 index 76897d2b0812..ee722177b4e4 100644 --- a/samples/client/petstore/powershell/src/IO.Swagger/API/PetApi.ps1 +++ b/samples/client/petstore/powershell/src/IO.Swagger/API/PetApi.ps1 @@ -3,7 +3,7 @@ function Invoke-PetApiAddPet { Param ( [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true)] [IO.Swagger.Model.Pet] - ${body} + ${pet} ) Process { @@ -11,7 +11,7 @@ function Invoke-PetApiAddPet { $PSBoundParameters | Out-DebugParameter | Write-Debug $Script:PetApi.AddPet( - ${body} + ${pet} ) } } @@ -97,7 +97,7 @@ function Invoke-PetApiUpdatePet { Param ( [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true)] [IO.Swagger.Model.Pet] - ${body} + ${pet} ) Process { @@ -105,7 +105,7 @@ function Invoke-PetApiUpdatePet { $PSBoundParameters | Out-DebugParameter | Write-Debug $Script:PetApi.UpdatePet( - ${body} + ${pet} ) } } diff --git a/samples/client/petstore/powershell/src/IO.Swagger/API/StoreApi.ps1 b/samples/client/petstore/powershell/src/IO.Swagger/API/StoreApi.ps1 index e1959279f4c7..411acb8295dd 100644 --- a/samples/client/petstore/powershell/src/IO.Swagger/API/StoreApi.ps1 +++ b/samples/client/petstore/powershell/src/IO.Swagger/API/StoreApi.ps1 @@ -53,7 +53,7 @@ function Invoke-StoreApiPlaceOrder { Param ( [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true)] [IO.Swagger.Model.Order] - ${body} + ${order} ) Process { @@ -61,7 +61,7 @@ function Invoke-StoreApiPlaceOrder { $PSBoundParameters | Out-DebugParameter | Write-Debug $Script:StoreApi.PlaceOrder( - ${body} + ${order} ) } } diff --git a/samples/client/petstore/powershell/src/IO.Swagger/API/UserApi.ps1 b/samples/client/petstore/powershell/src/IO.Swagger/API/UserApi.ps1 index dc47192292d2..b9c5d6ada5ed 100644 --- a/samples/client/petstore/powershell/src/IO.Swagger/API/UserApi.ps1 +++ b/samples/client/petstore/powershell/src/IO.Swagger/API/UserApi.ps1 @@ -3,7 +3,7 @@ function Invoke-UserApiCreateUser { Param ( [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true)] [IO.Swagger.Model.User] - ${body} + ${user} ) Process { @@ -11,7 +11,7 @@ function Invoke-UserApiCreateUser { $PSBoundParameters | Out-DebugParameter | Write-Debug $Script:UserApi.CreateUser( - ${body} + ${user} ) } } @@ -21,7 +21,7 @@ function Invoke-UserApiCreateUsersWithArrayInput { Param ( [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true)] [IO.Swagger.Model.User[]] - ${body} + ${user} ) Process { @@ -29,7 +29,7 @@ function Invoke-UserApiCreateUsersWithArrayInput { $PSBoundParameters | Out-DebugParameter | Write-Debug $Script:UserApi.CreateUsersWithArrayInput( - ${body} + ${user} ) } } @@ -39,7 +39,7 @@ function Invoke-UserApiCreateUsersWithListInput { Param ( [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true)] [IO.Swagger.Model.User[]] - ${body} + ${user} ) Process { @@ -47,7 +47,7 @@ function Invoke-UserApiCreateUsersWithListInput { $PSBoundParameters | Out-DebugParameter | Write-Debug $Script:UserApi.CreateUsersWithListInput( - ${body} + ${user} ) } } @@ -132,7 +132,7 @@ function Invoke-UserApiUpdateUser { ${username}, [Parameter(Position = 1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true)] [IO.Swagger.Model.User] - ${body} + ${user} ) Process { @@ -141,7 +141,7 @@ function Invoke-UserApiUpdateUser { $Script:UserApi.UpdateUser( ${username}, - ${body} + ${user} ) } } diff --git a/samples/client/petstore/powershell/src/IO.Swagger/en-US/about_IO.Swagger.help.txt b/samples/client/petstore/powershell/src/IO.Swagger/en-US/about_IO.Swagger.help.txt index d598279543b3..fd336809b3c0 100644 --- a/samples/client/petstore/powershell/src/IO.Swagger/en-US/about_IO.Swagger.help.txt +++ b/samples/client/petstore/powershell/src/IO.Swagger/en-US/about_IO.Swagger.help.txt @@ -11,8 +11,8 @@ LONG DESCRIPTION - API version: 1.0.0 - SDK version: - - Build date: 2017-06-20T22:49:00.415+08:00 - - Build package: io.swagger.codegen.languages.PowerShellClientCodegen + - Build date: 2018-04-12T00:40:01.530+08:00 + - Build package: org.openapitools.codegen.languages.PowerShellClientCodegen Frameworks supported: diff --git a/samples/client/petstore/qt5cpp/.swagger-codegen/VERSION b/samples/client/petstore/qt5cpp/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/qt5cpp/.swagger-codegen/VERSION +++ b/samples/client/petstore/qt5cpp/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp index cf07c4ca5ece..252f15bcf54c 100644 --- a/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp +++ b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp @@ -185,7 +185,7 @@ void PetApiTests::updatePetWithFormTest() { static SWGPetApi* api = getApi(); SWGPet* pet = createRandomPet(); - static SWGPet* petToCheck; + SWGPet* petToCheck; qint64 id = pet->getId(); static QEventLoop loop; QTimer timer; @@ -209,7 +209,7 @@ void PetApiTests::updatePetWithFormTest() { timer.setInterval(1000); timer.setSingleShot(true); - auto fetchPet = [](SWGPet* pet) { + auto fetchPet = [&](SWGPet* pet) { petToCheck = pet; loop.quit(); }; diff --git a/samples/client/petstore/qt5cpp/PetStore/PetStore.pro b/samples/client/petstore/qt5cpp/PetStore/PetStore.pro index 64f27a3c9249..ef2ef25ca2b8 100644 --- a/samples/client/petstore/qt5cpp/PetStore/PetStore.pro +++ b/samples/client/petstore/qt5cpp/PetStore/PetStore.pro @@ -16,33 +16,9 @@ CONFIG += c++11 TEMPLATE = app +include(../client/client.pri) SOURCES += main.cpp \ - ../client/SWGCategory.cpp \ - ../client/SWGHelpers.cpp \ - ../client/SWGHttpRequest.cpp \ - ../client/SWGOrder.cpp \ - ../client/SWGPet.cpp \ - ../client/SWGPetApi.cpp \ - ../client/SWGStoreApi.cpp \ - ../client/SWGTag.cpp \ - ../client/SWGUser.cpp \ - ../client/SWGUserApi.cpp \ - ../client/SWGApiResponse.cpp \ - PetApiTests.cpp - -HEADERS += \ - ../client/SWGCategory.h \ - ../client/SWGHelpers.h \ - ../client/SWGHttpRequest.h \ - ../client/SWGObject.h \ - ../client/SWGOrder.h \ - ../client/SWGPet.h \ - ../client/SWGPetApi.h \ - ../client/SWGStoreApi.h \ - ../client/SWGTag.h \ - ../client/SWGUser.h \ - ../client/SWGUserApi.h \ - PetApiTests.h \ - ../client/SWGApiResponse.h \ - ../client/SWGModelFactory.h + PetApiTests.cpp + +HEADERS += PetApiTests.h diff --git a/samples/client/petstore/qt5cpp/client/SWGOrder.cpp b/samples/client/petstore/qt5cpp/client/SWGOrder.cpp index 59184cbc12b2..dd9c9a6b9a87 100644 --- a/samples/client/petstore/qt5cpp/client/SWGOrder.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGOrder.cpp @@ -192,7 +192,6 @@ SWGOrder::isSet(){ if(m_id_isSet){ isObjectUpdated = true; break;} if(m_pet_id_isSet){ isObjectUpdated = true; break;} if(m_quantity_isSet){ isObjectUpdated = true; break;} - if(status != nullptr && *status != QString("")){ isObjectUpdated = true; break;} if(m_complete_isSet){ isObjectUpdated = true; break;} }while(false); diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp index 3dffe9c0695b..fea2b44e2447 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp @@ -13,6 +13,7 @@ #include "SWGPetApi.h" #include "SWGHelpers.h" #include "SWGModelFactory.h" +#include "SWGQObjectWrapper.h" #include #include @@ -29,7 +30,7 @@ SWGPetApi::SWGPetApi(QString host, QString basePath) { } void -SWGPetApi::addPet(SWGPet& body) { +SWGPetApi::addPet(SWGPet& swg_pet) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet"); @@ -40,7 +41,7 @@ SWGPetApi::addPet(SWGPet& body) { - QString output = body.asJson(); + QString output = swg_pet.asJson(); input.request_body.append(output); @@ -140,47 +141,13 @@ SWGPetApi::findPetsByStatus(QList* status) { fullPath.append(this->host).append(this->basePath).append("/pet/findByStatus"); - - - if (status->size() > 0) { - if (QString("csv").indexOf("multi") == 0) { - foreach(QString* t, *status) { - if (fullPath.indexOf("?") > 0) - fullPath.append("&"); - else - fullPath.append("?"); - fullPath.append("status=").append(stringValue(t)); - } - } - else if (QString("csv").indexOf("ssv") == 0) { - if (fullPath.indexOf("?") > 0) - fullPath.append("&"); - else - fullPath.append("?"); - fullPath.append("status="); - qint32 count = 0; - foreach(QString* t, *status) { - if (count > 0) { - fullPath.append(" "); - } - fullPath.append(stringValue(t)); - } - } - else if (QString("csv").indexOf("tsv") == 0) { - if (fullPath.indexOf("?") > 0) - fullPath.append("&"); - else - fullPath.append("?"); - fullPath.append("status="); - qint32 count = 0; - foreach(QString* t, *status) { - if (count > 0) { - fullPath.append("\t"); - } - fullPath.append(stringValue(t)); - } - } - } + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("status")) + .append("=") + .append(QUrl::toPercentEncoding(stringValue(status))); SWGHttpRequestWorker *worker = new SWGHttpRequestWorker(); @@ -220,15 +187,17 @@ SWGPetApi::findPetsByStatusCallback(SWGHttpRequestWorker * worker) { QByteArray array (json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonArray jsonArray = doc.array(); - + auto wrapper = new SWGQObjectWrapper*> (output); + wrapper->deleteLater(); foreach(QJsonValue obj, jsonArray) { SWGPet* o = new SWGPet(); QJsonObject jv = obj.toObject(); QJsonObject * ptr = (QJsonObject*)&jv; o->fromJsonObject(*ptr); + auto objwrapper = new SWGQObjectWrapper (o); + objwrapper->deleteLater(); output->append(o); } - worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { @@ -245,47 +214,13 @@ SWGPetApi::findPetsByTags(QList* tags) { fullPath.append(this->host).append(this->basePath).append("/pet/findByTags"); - - - if (tags->size() > 0) { - if (QString("csv").indexOf("multi") == 0) { - foreach(QString* t, *tags) { - if (fullPath.indexOf("?") > 0) - fullPath.append("&"); - else - fullPath.append("?"); - fullPath.append("tags=").append(stringValue(t)); - } - } - else if (QString("csv").indexOf("ssv") == 0) { - if (fullPath.indexOf("?") > 0) - fullPath.append("&"); - else - fullPath.append("?"); - fullPath.append("tags="); - qint32 count = 0; - foreach(QString* t, *tags) { - if (count > 0) { - fullPath.append(" "); - } - fullPath.append(stringValue(t)); - } - } - else if (QString("csv").indexOf("tsv") == 0) { - if (fullPath.indexOf("?") > 0) - fullPath.append("&"); - else - fullPath.append("?"); - fullPath.append("tags="); - qint32 count = 0; - foreach(QString* t, *tags) { - if (count > 0) { - fullPath.append("\t"); - } - fullPath.append(stringValue(t)); - } - } - } + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tags")) + .append("=") + .append(QUrl::toPercentEncoding(stringValue(tags))); SWGHttpRequestWorker *worker = new SWGHttpRequestWorker(); @@ -325,15 +260,17 @@ SWGPetApi::findPetsByTagsCallback(SWGHttpRequestWorker * worker) { QByteArray array (json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonArray jsonArray = doc.array(); - + auto wrapper = new SWGQObjectWrapper*> (output); + wrapper->deleteLater(); foreach(QJsonValue obj, jsonArray) { SWGPet* o = new SWGPet(); QJsonObject jv = obj.toObject(); QJsonObject * ptr = (QJsonObject*)&jv; o->fromJsonObject(*ptr); + auto objwrapper = new SWGQObjectWrapper (o); + objwrapper->deleteLater(); output->append(o); } - worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { @@ -385,9 +322,10 @@ SWGPetApi::getPetByIdCallback(SWGHttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - QString json(worker->response); SWGPet* output = static_cast(create(json, QString("SWGPet"))); + auto wrapper = new SWGQObjectWrapper (output); + wrapper->deleteLater(); worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { @@ -399,7 +337,7 @@ SWGPetApi::getPetByIdCallback(SWGHttpRequestWorker * worker) { } void -SWGPetApi::updatePet(SWGPet& body) { +SWGPetApi::updatePet(SWGPet& swg_pet) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet"); @@ -410,7 +348,7 @@ SWGPetApi::updatePet(SWGPet& body) { - QString output = body.asJson(); + QString output = swg_pet.asJson(); input.request_body.append(output); @@ -554,9 +492,10 @@ SWGPetApi::uploadFileCallback(SWGHttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - QString json(worker->response); SWGApiResponse* output = static_cast(create(json, QString("SWGApiResponse"))); + auto wrapper = new SWGQObjectWrapper (output); + wrapper->deleteLater(); worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.h b/samples/client/petstore/qt5cpp/client/SWGPetApi.h index ad40b90a8794..70ce602c51cb 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPetApi.h +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.h @@ -36,12 +36,12 @@ class SWGPetApi: public QObject { QString basePath; QMap defaultHeaders; - void addPet(SWGPet& body); + void addPet(SWGPet& swg_pet); void deletePet(qint64 pet_id, QString* api_key); void findPetsByStatus(QList* status); void findPetsByTags(QList* tags); void getPetById(qint64 pet_id); - void updatePet(SWGPet& body); + void updatePet(SWGPet& swg_pet); void updatePetWithForm(qint64 pet_id, QString* name, QString* status); void uploadFile(qint64 pet_id, QString* additional_metadata, SWGHttpRequestInputFileElement* file); diff --git a/samples/client/petstore/qt5cpp/client/SWGQObjectWrapper.h b/samples/client/petstore/qt5cpp/client/SWGQObjectWrapper.h new file mode 100644 index 000000000000..9252b5db2e2e --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGQObjectWrapper.h @@ -0,0 +1,35 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +#ifndef SWG_QOBJECT_WRAPPER_H +#define SWG_QOBJECT_WRAPPER_H + +#include + +namespace Swagger { + + template + class SWGQObjectWrapper : public QObject { + public: + SWGQObjectWrapper(ObjectPtrT ptr){ + data = ptr; + } + ~SWGQObjectWrapper(){ + delete data; + } + private : + ObjectPtrT data; + }; + +} + +#endif // SWG_QOBJECT_WRAPPER_H \ No newline at end of file diff --git a/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp b/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp index 3b38f5710a25..b04e57e273b0 100644 --- a/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp @@ -13,6 +13,7 @@ #include "SWGStoreApi.h" #include "SWGHelpers.h" #include "SWGModelFactory.h" +#include "SWGQObjectWrapper.h" #include #include @@ -118,7 +119,6 @@ SWGStoreApi::getInventoryCallback(SWGHttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - QMap* output = new QMap(); QString json(worker->response); QByteArray array (json.toStdString().c_str()); @@ -126,9 +126,9 @@ SWGStoreApi::getInventoryCallback(SWGHttpRequestWorker * worker) { QJsonObject obj = doc.object(); foreach(QString key, obj.keys()) { - qint32* val; + qint32 val; setValue(&val, obj[key], "qint32", QString()); - output->insert(key, *val); + output->insert(key, val); } worker->deleteLater(); @@ -181,9 +181,10 @@ SWGStoreApi::getOrderByIdCallback(SWGHttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - QString json(worker->response); SWGOrder* output = static_cast(create(json, QString("SWGOrder"))); + auto wrapper = new SWGQObjectWrapper (output); + wrapper->deleteLater(); worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { @@ -195,7 +196,7 @@ SWGStoreApi::getOrderByIdCallback(SWGHttpRequestWorker * worker) { } void -SWGStoreApi::placeOrder(SWGOrder& body) { +SWGStoreApi::placeOrder(SWGOrder& swg_order) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/store/order"); @@ -206,7 +207,7 @@ SWGStoreApi::placeOrder(SWGOrder& body) { - QString output = body.asJson(); + QString output = swg_order.asJson(); input.request_body.append(output); @@ -236,9 +237,10 @@ SWGStoreApi::placeOrderCallback(SWGHttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - QString json(worker->response); SWGOrder* output = static_cast(create(json, QString("SWGOrder"))); + auto wrapper = new SWGQObjectWrapper (output); + wrapper->deleteLater(); worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { diff --git a/samples/client/petstore/qt5cpp/client/SWGStoreApi.h b/samples/client/petstore/qt5cpp/client/SWGStoreApi.h index c6d9acc5a26e..321a0e609280 100644 --- a/samples/client/petstore/qt5cpp/client/SWGStoreApi.h +++ b/samples/client/petstore/qt5cpp/client/SWGStoreApi.h @@ -38,7 +38,7 @@ class SWGStoreApi: public QObject { void deleteOrder(QString* order_id); void getInventory(); void getOrderById(qint64 order_id); - void placeOrder(SWGOrder& body); + void placeOrder(SWGOrder& swg_order); private: void deleteOrderCallback (SWGHttpRequestWorker * worker); diff --git a/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp b/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp index 328e1e82d3a0..bb02a3d5de61 100644 --- a/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp @@ -13,6 +13,7 @@ #include "SWGUserApi.h" #include "SWGHelpers.h" #include "SWGModelFactory.h" +#include "SWGQObjectWrapper.h" #include #include @@ -29,7 +30,7 @@ SWGUserApi::SWGUserApi(QString host, QString basePath) { } void -SWGUserApi::createUser(SWGUser& body) { +SWGUserApi::createUser(SWGUser& swg_user) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user"); @@ -40,7 +41,7 @@ SWGUserApi::createUser(SWGUser& body) { - QString output = body.asJson(); + QString output = swg_user.asJson(); input.request_body.append(output); @@ -81,7 +82,7 @@ SWGUserApi::createUserCallback(SWGHttpRequestWorker * worker) { } void -SWGUserApi::createUsersWithArrayInput(QList*& body) { +SWGUserApi::createUsersWithArrayInput(QList*& swg_user) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/createWithArray"); @@ -91,10 +92,10 @@ SWGUserApi::createUsersWithArrayInput(QList*& body) { SWGHttpRequestInput input(fullPath, "POST"); - QJsonObject body_jobj; - toJsonArray((QList*)body, body_jobj, QString("body"), QString("SWGUser*")); + QJsonObject swg_user_jobj; + toJsonArray((QList*)swg_user, swg_user_jobj, QString("body"), QString("SWGUser*")); - QJsonDocument doc(body_jobj); + QJsonDocument doc(swg_user_jobj); QByteArray bytes = doc.toJson(); input.request_body.append(bytes); @@ -137,7 +138,7 @@ SWGUserApi::createUsersWithArrayInputCallback(SWGHttpRequestWorker * worker) { } void -SWGUserApi::createUsersWithListInput(QList*& body) { +SWGUserApi::createUsersWithListInput(QList*& swg_user) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/createWithList"); @@ -147,10 +148,10 @@ SWGUserApi::createUsersWithListInput(QList*& body) { SWGHttpRequestInput input(fullPath, "POST"); - QJsonObject body_jobj; - toJsonArray((QList*)body, body_jobj, QString("body"), QString("SWGUser*")); + QJsonObject swg_user_jobj; + toJsonArray((QList*)swg_user, swg_user_jobj, QString("body"), QString("SWGUser*")); - QJsonDocument doc(body_jobj); + QJsonDocument doc(swg_user_jobj); QByteArray bytes = doc.toJson(); input.request_body.append(bytes); @@ -284,9 +285,10 @@ SWGUserApi::getUserByNameCallback(SWGHttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - QString json(worker->response); SWGUser* output = static_cast(create(json, QString("SWGUser"))); + auto wrapper = new SWGQObjectWrapper (output); + wrapper->deleteLater(); worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { @@ -352,9 +354,10 @@ SWGUserApi::loginUserCallback(SWGHttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - QString json(worker->response); QString* output = static_cast(create(json, QString("QString"))); + auto wrapper = new SWGQObjectWrapper (output); + wrapper->deleteLater(); worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { @@ -415,7 +418,7 @@ SWGUserApi::logoutUserCallback(SWGHttpRequestWorker * worker) { } void -SWGUserApi::updateUser(QString* username, SWGUser& body) { +SWGUserApi::updateUser(QString* username, SWGUser& swg_user) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/{username}"); @@ -428,7 +431,7 @@ SWGUserApi::updateUser(QString* username, SWGUser& body) { - QString output = body.asJson(); + QString output = swg_user.asJson(); input.request_body.append(output); diff --git a/samples/client/petstore/qt5cpp/client/SWGUserApi.h b/samples/client/petstore/qt5cpp/client/SWGUserApi.h index a667e85dee74..e6ad3c2e0926 100644 --- a/samples/client/petstore/qt5cpp/client/SWGUserApi.h +++ b/samples/client/petstore/qt5cpp/client/SWGUserApi.h @@ -15,7 +15,6 @@ #include "SWGHttpRequest.h" -#include #include #include "SWGUser.h" @@ -35,14 +34,14 @@ class SWGUserApi: public QObject { QString basePath; QMap defaultHeaders; - void createUser(SWGUser& body); - void createUsersWithArrayInput(QList*& body); - void createUsersWithListInput(QList*& body); + void createUser(SWGUser& swg_user); + void createUsersWithArrayInput(QList*& swg_user); + void createUsersWithListInput(QList*& swg_user); void deleteUser(QString* username); void getUserByName(QString* username); void loginUser(QString* username, QString* password); void logoutUser(); - void updateUser(QString* username, SWGUser& body); + void updateUser(QString* username, SWGUser& swg_user); private: void createUserCallback (SWGHttpRequestWorker * worker); diff --git a/samples/client/petstore/qt5cpp/client/client.pri b/samples/client/petstore/qt5cpp/client/client.pri new file mode 100644 index 000000000000..c4202c44aee0 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/client.pri @@ -0,0 +1,37 @@ +QT += network + +HEADERS += \ +# Models + $${PWD}/SWGApiResponse.h \ + $${PWD}/SWGCategory.h \ + $${PWD}/SWGOrder.h \ + $${PWD}/SWGPet.h \ + $${PWD}/SWGTag.h \ + $${PWD}/SWGUser.h \ +# APIs + $${PWD}/SWGPetApi.h \ + $${PWD}/SWGStoreApi.h \ + $${PWD}/SWGUserApi.h \ +# Others + $${PWD}/SWGHelpers.h \ + $${PWD}/SWGHttpRequest.h \ + $${PWD}/SWGModelFactory.h \ + $${PWD}/SWGObject.h \ + $${PWD}/SWGQObjectWrapper.h + +SOURCES += \ +# Models + $${PWD}/SWGApiResponse.cpp \ + $${PWD}/SWGCategory.cpp \ + $${PWD}/SWGOrder.cpp \ + $${PWD}/SWGPet.cpp \ + $${PWD}/SWGTag.cpp \ + $${PWD}/SWGUser.cpp \ +# APIs + $${PWD}/SWGPetApi.cpp \ + $${PWD}/SWGStoreApi.cpp \ + $${PWD}/SWGUserApi.cpp \ +# Others + $${PWD}/SWGHelpers.cpp \ + $${PWD}/SWGHttpRequest.cpp + diff --git a/samples/client/petstore/r_test/.swagger-codegen/VERSION b/samples/client/petstore/r_test/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/client/petstore/r_test/.swagger-codegen/VERSION +++ b/samples/client/petstore/r_test/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/r_test/R/ApiResponse.r b/samples/client/petstore/r_test/R/ApiResponse.r index d8a182d24630..62e7456e6210 100644 --- a/samples/client/petstore/r_test/R/ApiResponse.r +++ b/samples/client/petstore/r_test/R/ApiResponse.r @@ -65,7 +65,7 @@ ApiResponse <- R6::R6Class( toJSONString = function() { sprintf( '{ - "code": %s, + "code": %d, "type": %s, "message": %s }', diff --git a/samples/client/petstore/r_test/R/Order.r b/samples/client/petstore/r_test/R/Order.r index d7054e2458c1..6cbf1987d40b 100644 --- a/samples/client/petstore/r_test/R/Order.r +++ b/samples/client/petstore/r_test/R/Order.r @@ -102,7 +102,7 @@ Order <- R6::R6Class( '{ "id": %d, "petId": %d, - "quantity": %s, + "quantity": %d, "shipDate": %s, "status": %s, "complete": %s diff --git a/samples/client/petstore/r_test/R/PetApi.r b/samples/client/petstore/r_test/R/PetApi.r index 286143a733b2..0e167c1fc4df 100644 --- a/samples/client/petstore/r_test/R/PetApi.r +++ b/samples/client/petstore/r_test/R/PetApi.r @@ -57,13 +57,13 @@ PetApi <- R6::R6Class( self$apiClient <- ApiClient$new() } }, - add_pet = function(body, ...){ + add_pet = function(pet, ...){ args <- list(...) queryParams <- list() headerParams <- character() - if (!missing(`body`)) { - body <- `body`$toJSONString() + if (!missing(`pet`)) { + body <- `pet`$toJSONString() } else { body <- NULL } @@ -199,13 +199,13 @@ PetApi <- R6::R6Class( } }, - update_pet = function(body, ...){ + update_pet = function(pet, ...){ args <- list(...) queryParams <- list() headerParams <- character() - if (!missing(`body`)) { - body <- `body`$toJSONString() + if (!missing(`pet`)) { + body <- `pet`$toJSONString() } else { body <- NULL } diff --git a/samples/client/petstore/r_test/R/StoreApi.r b/samples/client/petstore/r_test/R/StoreApi.r index 5fe600252419..3bca08610a19 100644 --- a/samples/client/petstore/r_test/R/StoreApi.r +++ b/samples/client/petstore/r_test/R/StoreApi.r @@ -123,13 +123,13 @@ StoreApi <- R6::R6Class( } }, - place_order = function(body, ...){ + place_order = function(order, ...){ args <- list(...) queryParams <- list() headerParams <- character() - if (!missing(`body`)) { - body <- `body`$toJSONString() + if (!missing(`order`)) { + body <- `order`$toJSONString() } else { body <- NULL } diff --git a/samples/client/petstore/r_test/R/User.r b/samples/client/petstore/r_test/R/User.r index 9df47561c2e6..12587b5f9cb6 100644 --- a/samples/client/petstore/r_test/R/User.r +++ b/samples/client/petstore/r_test/R/User.r @@ -132,7 +132,7 @@ User <- R6::R6Class( "email": %s, "password": %s, "phone": %s, - "userStatus": %s + "userStatus": %d }', self$`id`, self$`username`, diff --git a/samples/client/petstore/r_test/R/UserApi.r b/samples/client/petstore/r_test/R/UserApi.r index c25bea180487..c5036a3058df 100644 --- a/samples/client/petstore/r_test/R/UserApi.r +++ b/samples/client/petstore/r_test/R/UserApi.r @@ -57,13 +57,13 @@ UserApi <- R6::R6Class( self$apiClient <- ApiClient$new() } }, - create_user = function(body, ...){ + create_user = function(user, ...){ args <- list(...) queryParams <- list() headerParams <- character() - if (!missing(`body`)) { - body <- `body`$toJSONString() + if (!missing(`user`)) { + body <- `user`$toJSONString() } else { body <- NULL } @@ -85,13 +85,13 @@ UserApi <- R6::R6Class( } }, - create_users_with_array_input = function(body, ...){ + create_users_with_array_input = function(user, ...){ args <- list(...) queryParams <- list() headerParams <- character() - if (!missing(`body`)) { - body <- `body`$toJSONString() + if (!missing(`user`)) { + body <- `user`$toJSONString() } else { body <- NULL } @@ -113,13 +113,13 @@ UserApi <- R6::R6Class( } }, - create_users_with_list_input = function(body, ...){ + create_users_with_list_input = function(user, ...){ args <- list(...) queryParams <- list() headerParams <- character() - if (!missing(`body`)) { - body <- `body`$toJSONString() + if (!missing(`user`)) { + body <- `user`$toJSONString() } else { body <- NULL } @@ -249,13 +249,13 @@ UserApi <- R6::R6Class( } }, - update_user = function(username, body, ...){ + update_user = function(username, user, ...){ args <- list(...) queryParams <- list() headerParams <- character() - if (!missing(`body`)) { - body <- `body`$toJSONString() + if (!missing(`user`)) { + body <- `user`$toJSONString() } else { body <- NULL } diff --git a/samples/client/petstore/r_test/README.md b/samples/client/petstore/r_test/README.md index c4b8e4bf0e7f..a314cda76441 100644 --- a/samples/client/petstore/r_test/README.md +++ b/samples/client/petstore/r_test/README.md @@ -7,7 +7,7 @@ This API client was generated by the [swagger-codegen](https://github.com/swagge - API version: 1.0.0 - Package version: 1.0.0 -- Build package: io.swagger.codegen.languages.RClientCodegen +- Build package: org.openapitools.codegen.languages.RClientCodegen ## Installation You'll need the `devtools` package in order to build the API. diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 604619901764..4b360b0042c7 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -55,13 +55,11 @@ Please follow the [installation](#installation) procedure and then run the follo require 'petstore' api_instance = Petstore::AnotherFakeApi.new - -body = Petstore::Client.new # Client | client model - +client = Petstore::Client.new # Client | client model begin #To test special tags - result = api_instance.test_special_tags(body) + result = api_instance.test_special_tags(client) p result rescue Petstore::ApiError => e puts "Exception when calling AnotherFakeApi->test_special_tags: #{e}" @@ -117,10 +115,13 @@ Class | Method | HTTP request | Description - [Petstore::ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [Petstore::ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [Petstore::ArrayTest](docs/ArrayTest.md) + - [Petstore::Body4](docs/Body4.md) - [Petstore::Capitalization](docs/Capitalization.md) + - [Petstore::Cat](docs/Cat.md) - [Petstore::Category](docs/Category.md) - [Petstore::ClassModel](docs/ClassModel.md) - [Petstore::Client](docs/Client.md) + - [Petstore::Dog](docs/Dog.md) - [Petstore::EnumArrays](docs/EnumArrays.md) - [Petstore::EnumClass](docs/EnumClass.md) - [Petstore::EnumTest](docs/EnumTest.md) @@ -144,8 +145,6 @@ Class | Method | HTTP request | Description - [Petstore::SpecialModelName](docs/SpecialModelName.md) - [Petstore::Tag](docs/Tag.md) - [Petstore::User](docs/User.md) - - [Petstore::Cat](docs/Cat.md) - - [Petstore::Dog](docs/Dog.md) ## Documentation for Authorization diff --git a/samples/client/petstore/ruby/docs/AnotherFakeApi.md b/samples/client/petstore/ruby/docs/AnotherFakeApi.md index a198df230eba..8163b2b49dac 100644 --- a/samples/client/petstore/ruby/docs/AnotherFakeApi.md +++ b/samples/client/petstore/ruby/docs/AnotherFakeApi.md @@ -8,7 +8,7 @@ Method | HTTP request | Description # **test_special_tags** -> Client test_special_tags(body) +> Client test_special_tags(client) To test special tags @@ -20,13 +20,11 @@ To test special tags require 'petstore' api_instance = Petstore::AnotherFakeApi.new - -body = Petstore::Client.new # Client | client model - +client = Petstore::Client.new # Client | client model begin #To test special tags - result = api_instance.test_special_tags(body) + result = api_instance.test_special_tags(client) p result rescue Petstore::ApiError => e puts "Exception when calling AnotherFakeApi->test_special_tags: #{e}" @@ -37,7 +35,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | + **client** | [**Client**](Client.md)| client model | ### Return type @@ -49,7 +47,7 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json + - **Content-Type**: Not defined - **Accept**: application/json diff --git a/samples/client/petstore/ruby/docs/200Response.md b/samples/client/petstore/ruby/docs/Body4.md similarity index 55% rename from samples/client/petstore/ruby/docs/200Response.md rename to samples/client/petstore/ruby/docs/Body4.md index 2e0f1ec92f36..618b2f3de3ab 100644 --- a/samples/client/petstore/ruby/docs/200Response.md +++ b/samples/client/petstore/ruby/docs/Body4.md @@ -1,8 +1,9 @@ -# Petstore::200Response +# Petstore::Body4 ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**name** | **Integer** | | [optional] +**param** | **String** | field1 | +**param2** | **String** | field2 | diff --git a/samples/client/petstore/ruby/docs/EnumTest.md b/samples/client/petstore/ruby/docs/EnumTest.md index 5ca83b3f77dd..87297ac476ed 100644 --- a/samples/client/petstore/ruby/docs/EnumTest.md +++ b/samples/client/petstore/ruby/docs/EnumTest.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **enum_string** | **String** | | [optional] +**enum_string_required** | **String** | | **enum_integer** | **Integer** | | [optional] **enum_number** | **Float** | | [optional] **outer_enum** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index cd4df08108ed..3395ff2b344d 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -28,9 +28,8 @@ Test serialization of outer boolean types require 'petstore' api_instance = Petstore::FakeApi.new - -opts = { - body: Petstore::OuterBoolean.new # OuterBoolean | Input boolean as post body +opts = { + body: true # BOOLEAN | Input boolean as post body } begin @@ -45,7 +44,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OuterBoolean**](OuterBoolean.md)| Input boolean as post body | [optional] + **body** | **BOOLEAN**| Input boolean as post body | [optional] ### Return type @@ -57,8 +56,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined + - **Content-Type**: application/json + - **Accept**: */* @@ -75,9 +74,8 @@ Test serialization of object with outer number type require 'petstore' api_instance = Petstore::FakeApi.new - -opts = { - body: Petstore::OuterComposite.new # OuterComposite | Input composite as post body +opts = { + outer_composite: Petstore::OuterComposite.new # OuterComposite | Input composite as post body } begin @@ -92,7 +90,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] + **outer_composite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] ### Return type @@ -104,8 +102,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined + - **Content-Type**: application/json + - **Accept**: */* @@ -122,9 +120,8 @@ Test serialization of outer number types require 'petstore' api_instance = Petstore::FakeApi.new - -opts = { - body: Petstore::OuterNumber.new # OuterNumber | Input number as post body +opts = { + body: 3.4 # Float | Input number as post body } begin @@ -139,7 +136,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OuterNumber**](OuterNumber.md)| Input number as post body | [optional] + **body** | **Float**| Input number as post body | [optional] ### Return type @@ -151,8 +148,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined + - **Content-Type**: application/json + - **Accept**: */* @@ -169,9 +166,8 @@ Test serialization of outer string types require 'petstore' api_instance = Petstore::FakeApi.new - -opts = { - body: Petstore::OuterString.new # OuterString | Input string as post body +opts = { + body: 'body_example' # String | Input string as post body } begin @@ -186,7 +182,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OuterString**](OuterString.md)| Input string as post body | [optional] + **body** | **String**| Input string as post body | [optional] ### Return type @@ -198,13 +194,13 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined + - **Content-Type**: application/json + - **Accept**: */* # **test_client_model** -> Client test_client_model(body) +> Client test_client_model(client) To test \"client\" model @@ -216,13 +212,11 @@ To test \"client\" model require 'petstore' api_instance = Petstore::FakeApi.new - -body = Petstore::Client.new # Client | client model - +client = Petstore::Client.new # Client | client model begin #To test \"client\" model - result = api_instance.test_client_model(body) + result = api_instance.test_client_model(client) p result rescue Petstore::ApiError => e puts "Exception when calling FakeApi->test_client_model: #{e}" @@ -233,7 +227,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | + **client** | [**Client**](Client.md)| client model | ### Return type @@ -245,7 +239,7 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json + - **Content-Type**: Not defined - **Accept**: application/json @@ -269,22 +263,17 @@ Petstore.configure do |config| end api_instance = Petstore::FakeApi.new - -number = 8.14 # Float | None - -double = 1.2 # Float | None - +number = 3.4 # Float | None +double = 3.4 # Float | None pattern_without_delimiter = 'pattern_without_delimiter_example' # String | None - -byte = 'B' # String | None - -opts = { +byte = 'byte_example' # String | None +opts = { integer: 56, # Integer | None int32: 56, # Integer | None - int64: 789, # Integer | None + int64: 56, # Integer | None float: 3.4, # Float | None string: 'string_example', # String | None - binary: 'B', # String | None + binary: File.new('/path/to/file'), # File | None date: Date.parse('2013-10-20'), # Date | None date_time: DateTime.parse('2013-10-20T19:20:30+01:00'), # DateTime | None password: 'password_example', # String | None @@ -312,7 +301,7 @@ Name | Type | Description | Notes **int64** | **Integer**| None | [optional] **float** | **Float**| None | [optional] **string** | **String**| None | [optional] - **binary** | **String**| None | [optional] + **binary** | **File**| None | [optional] **date** | **Date**| None | [optional] **date_time** | **DateTime**| None | [optional] **password** | **String**| None | [optional] @@ -328,8 +317,8 @@ nil (empty response body) ### HTTP request headers - - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined @@ -346,16 +335,15 @@ To test enum parameters require 'petstore' api_instance = Petstore::FakeApi.new - -opts = { - enum_form_string_array: ['enum_form_string_array_example'], # Array | Form parameter enum test (string array) - enum_form_string: '-efg', # String | Form parameter enum test (string) +opts = { enum_header_string_array: ['enum_header_string_array_example'], # Array | Header parameter enum test (string array) - enum_header_string: '-efg', # String | Header parameter enum test (string) + enum_header_string: 'enum_header_string_example', # String | Header parameter enum test (string) enum_query_string_array: ['enum_query_string_array_example'], # Array | Query parameter enum test (string array) - enum_query_string: '-efg', # String | Query parameter enum test (string) + enum_query_string: 'enum_query_string_example', # String | Query parameter enum test (string) enum_query_integer: 56, # Integer | Query parameter enum test (double) - enum_query_double: 1.2 # Float | Query parameter enum test (double) + enum_query_double: 1.2, # Float | Query parameter enum test (double) + enum_form_string_array: nil, # Array | Form parameter enum test (string array) + enum_form_string: 'enum_form_string_example' # String | Form parameter enum test (string) } begin @@ -370,14 +358,14 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **enum_form_string_array** | [**Array<String>**](String.md)| Form parameter enum test (string array) | [optional] - **enum_form_string** | **String**| Form parameter enum test (string) | [optional] [default to -efg] **enum_header_string_array** | [**Array<String>**](String.md)| Header parameter enum test (string array) | [optional] - **enum_header_string** | **String**| Header parameter enum test (string) | [optional] [default to -efg] + **enum_header_string** | **String**| Header parameter enum test (string) | [optional] **enum_query_string_array** | [**Array<String>**](String.md)| Query parameter enum test (string array) | [optional] - **enum_query_string** | **String**| Query parameter enum test (string) | [optional] [default to -efg] + **enum_query_string** | **String**| Query parameter enum test (string) | [optional] **enum_query_integer** | **Integer**| Query parameter enum test (double) | [optional] **enum_query_double** | **Float**| Query parameter enum test (double) | [optional] + **enum_form_string_array** | [**Array<String>**](Array.md)| Form parameter enum test (string array) | [optional] + **enum_form_string** | **String**| Form parameter enum test (string) | [optional] ### Return type @@ -389,31 +377,27 @@ No authorization required ### HTTP request headers - - **Content-Type**: */* - - **Accept**: */* + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined # **test_inline_additional_properties** -> test_inline_additional_properties(param) +> test_inline_additional_properties(unknown_base_type) test inline additionalProperties - - ### Example ```ruby # load the gem require 'petstore' api_instance = Petstore::FakeApi.new - -param = nil # Object | request body - +unknown_base_type = Petstore::UNKNOWN_BASE_TYPE.new # Hash | request body begin #test inline additionalProperties - api_instance.test_inline_additional_properties(param) + api_instance.test_inline_additional_properties(unknown_base_type) rescue Petstore::ApiError => e puts "Exception when calling FakeApi->test_inline_additional_properties: #{e}" end @@ -423,7 +407,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | **Object**| request body | + **unknown_base_type** | [**Hash<String, String>**](UNKNOWN_BASE_TYPE.md)| request body | ### Return type @@ -441,27 +425,23 @@ No authorization required # **test_json_form_data** -> test_json_form_data(param, param2) +> test_json_form_data(opts) test json serialization of form data - - ### Example ```ruby # load the gem require 'petstore' api_instance = Petstore::FakeApi.new - -param = 'param_example' # String | field1 - -param2 = 'param2_example' # String | field2 - +opts = { + body4: Petstore::Body4.new # Body4 | +} begin #test json serialization of form data - api_instance.test_json_form_data(param, param2) + api_instance.test_json_form_data(opts) rescue Petstore::ApiError => e puts "Exception when calling FakeApi->test_json_form_data: #{e}" end @@ -471,8 +451,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | **String**| field1 | - **param2** | **String**| field2 | + **body4** | [**Body4**](Body4.md)| | [optional] ### Return type diff --git a/samples/client/petstore/ruby/docs/FakeClassnameTags123Api.md b/samples/client/petstore/ruby/docs/FakeClassnameTags123Api.md index 1237031fb075..884a359c062b 100644 --- a/samples/client/petstore/ruby/docs/FakeClassnameTags123Api.md +++ b/samples/client/petstore/ruby/docs/FakeClassnameTags123Api.md @@ -8,7 +8,7 @@ Method | HTTP request | Description # **test_classname** -> Client test_classname(body) +> Client test_classname(client) To test class name in snake case @@ -27,13 +27,11 @@ Petstore.configure do |config| end api_instance = Petstore::FakeClassnameTags123Api.new - -body = Petstore::Client.new # Client | client model - +client = Petstore::Client.new # Client | client model begin #To test class name in snake case - result = api_instance.test_classname(body) + result = api_instance.test_classname(client) p result rescue Petstore::ApiError => e puts "Exception when calling FakeClassnameTags123Api->test_classname: #{e}" @@ -44,7 +42,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | + **client** | [**Client**](Client.md)| client model | ### Return type @@ -56,7 +54,7 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: application/json + - **Content-Type**: Not defined - **Accept**: application/json diff --git a/samples/client/petstore/ruby/docs/FormatTest.md b/samples/client/petstore/ruby/docs/FormatTest.md index 79cf9b5a8663..ad9b8191dceb 100644 --- a/samples/client/petstore/ruby/docs/FormatTest.md +++ b/samples/client/petstore/ruby/docs/FormatTest.md @@ -11,7 +11,7 @@ Name | Type | Description | Notes **double** | **Float** | | [optional] **string** | **String** | | [optional] **byte** | **String** | | -**binary** | **String** | | [optional] +**binary** | **File** | | [optional] **date** | **Date** | | **date_time** | **DateTime** | | [optional] **uuid** | **String** | | [optional] diff --git a/samples/client/petstore/ruby/docs/InlineResponse200.md b/samples/client/petstore/ruby/docs/InlineResponse200.md deleted file mode 100644 index c3b0d978c072..000000000000 --- a/samples/client/petstore/ruby/docs/InlineResponse200.md +++ /dev/null @@ -1,13 +0,0 @@ -# Petstore::InlineResponse200 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**tags** | [**Array<Tag>**](Tag.md) | | [optional] -**id** | **Integer** | | -**category** | **Object** | | [optional] -**status** | **String** | pet status in the store | [optional] -**name** | **String** | | [optional] -**photo_urls** | **Array<String>** | | [optional] - - diff --git a/samples/client/petstore/ruby/docs/PetApi.md b/samples/client/petstore/ruby/docs/PetApi.md index b76ad396d868..d806da3b0751 100644 --- a/samples/client/petstore/ruby/docs/PetApi.md +++ b/samples/client/petstore/ruby/docs/PetApi.md @@ -15,12 +15,10 @@ Method | HTTP request | Description # **add_pet** -> add_pet(body) +> add_pet(pet) Add a new pet to the store - - ### Example ```ruby # load the gem @@ -32,13 +30,11 @@ Petstore.configure do |config| end api_instance = Petstore::PetApi.new - -body = Petstore::Pet.new # Pet | Pet object that needs to be added to the store - +pet = Petstore::Pet.new # Pet | Pet object that needs to be added to the store begin #Add a new pet to the store - api_instance.add_pet(body) + api_instance.add_pet(pet) rescue Petstore::ApiError => e puts "Exception when calling PetApi->add_pet: #{e}" end @@ -48,7 +44,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -60,8 +56,8 @@ nil (empty response body) ### HTTP request headers - - **Content-Type**: application/json, application/xml - - **Accept**: application/xml, application/json + - **Content-Type**: Not defined + - **Accept**: Not defined @@ -70,8 +66,6 @@ nil (empty response body) Deletes a pet - - ### Example ```ruby # load the gem @@ -83,10 +77,8 @@ Petstore.configure do |config| end api_instance = Petstore::PetApi.new - pet_id = 789 # Integer | Pet id to delete - -opts = { +opts = { api_key: 'api_key_example' # String | } @@ -116,7 +108,7 @@ nil (empty response body) ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Accept**: Not defined @@ -138,10 +130,8 @@ Petstore.configure do |config| end api_instance = Petstore::PetApi.new - status = ['status_example'] # Array | Status values that need to be considered for filter - begin #Finds Pets by status result = api_instance.find_pets_by_status(status) @@ -190,10 +180,8 @@ Petstore.configure do |config| end api_instance = Petstore::PetApi.new - tags = ['tags_example'] # Array | Tags to filter by - begin #Finds Pets by tags result = api_instance.find_pets_by_tags(tags) @@ -244,10 +232,8 @@ Petstore.configure do |config| end api_instance = Petstore::PetApi.new - pet_id = 789 # Integer | ID of pet to return - begin #Find pet by ID result = api_instance.get_pet_by_id(pet_id) @@ -279,12 +265,10 @@ Name | Type | Description | Notes # **update_pet** -> update_pet(body) +> update_pet(pet) Update an existing pet - - ### Example ```ruby # load the gem @@ -296,13 +280,11 @@ Petstore.configure do |config| end api_instance = Petstore::PetApi.new - -body = Petstore::Pet.new # Pet | Pet object that needs to be added to the store - +pet = Petstore::Pet.new # Pet | Pet object that needs to be added to the store begin #Update an existing pet - api_instance.update_pet(body) + api_instance.update_pet(pet) rescue Petstore::ApiError => e puts "Exception when calling PetApi->update_pet: #{e}" end @@ -312,7 +294,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -324,8 +306,8 @@ nil (empty response body) ### HTTP request headers - - **Content-Type**: application/json, application/xml - - **Accept**: application/xml, application/json + - **Content-Type**: Not defined + - **Accept**: Not defined @@ -334,8 +316,6 @@ nil (empty response body) Updates a pet in the store with form data - - ### Example ```ruby # load the gem @@ -347,10 +327,8 @@ Petstore.configure do |config| end api_instance = Petstore::PetApi.new - pet_id = 789 # Integer | ID of pet that needs to be updated - -opts = { +opts = { name: 'name_example', # String | Updated name of the pet status: 'status_example' # String | Updated status of the pet } @@ -382,7 +360,7 @@ nil (empty response body) ### HTTP request headers - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: application/xml, application/json + - **Accept**: Not defined @@ -391,8 +369,6 @@ nil (empty response body) uploads an image - - ### Example ```ruby # load the gem @@ -404,12 +380,10 @@ Petstore.configure do |config| end api_instance = Petstore::PetApi.new - pet_id = 789 # Integer | ID of pet to update - -opts = { +opts = { additional_metadata: 'additional_metadata_example', # String | Additional data to pass to server - file: File.new('/path/to/file.txt') # File | file to upload + file: File.new('/path/to/file') # File | file to upload } begin diff --git a/samples/client/petstore/ruby/docs/StoreApi.md b/samples/client/petstore/ruby/docs/StoreApi.md index 8a6453c649c8..db87e05b34f0 100644 --- a/samples/client/petstore/ruby/docs/StoreApi.md +++ b/samples/client/petstore/ruby/docs/StoreApi.md @@ -23,10 +23,8 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non require 'petstore' api_instance = Petstore::StoreApi.new - order_id = 'order_id_example' # String | ID of the order that needs to be deleted - begin #Delete purchase order by ID api_instance.delete_order(order_id) @@ -52,7 +50,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Accept**: Not defined @@ -117,10 +115,8 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge require 'petstore' api_instance = Petstore::StoreApi.new - order_id = 789 # Integer | ID of pet that needs to be fetched - begin #Find purchase order by ID result = api_instance.get_order_by_id(order_id) @@ -152,25 +148,21 @@ No authorization required # **place_order** -> Order place_order(body) +> Order place_order(order) Place an order for a pet - - ### Example ```ruby # load the gem require 'petstore' api_instance = Petstore::StoreApi.new - -body = Petstore::Order.new # Order | order placed for purchasing the pet - +order = Petstore::Order.new # Order | order placed for purchasing the pet begin #Place an order for a pet - result = api_instance.place_order(body) + result = api_instance.place_order(order) p result rescue Petstore::ApiError => e puts "Exception when calling StoreApi->place_order: #{e}" @@ -181,7 +173,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Order**](Order.md)| order placed for purchasing the pet | + **order** | [**Order**](Order.md)| order placed for purchasing the pet | ### Return type @@ -193,7 +185,7 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined + - **Content-Type**: application/json - **Accept**: application/xml, application/json diff --git a/samples/client/petstore/ruby/docs/UserApi.md b/samples/client/petstore/ruby/docs/UserApi.md index 3c2da6869147..94d9fdd28529 100644 --- a/samples/client/petstore/ruby/docs/UserApi.md +++ b/samples/client/petstore/ruby/docs/UserApi.md @@ -15,7 +15,7 @@ Method | HTTP request | Description # **create_user** -> create_user(body) +> create_user(user) Create user @@ -27,13 +27,11 @@ This can only be done by the logged in user. require 'petstore' api_instance = Petstore::UserApi.new - -body = Petstore::User.new # User | Created user object - +user = Petstore::User.new # User | Created user object begin #Create user - api_instance.create_user(body) + api_instance.create_user(user) rescue Petstore::ApiError => e puts "Exception when calling UserApi->create_user: #{e}" end @@ -43,7 +41,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**User**](User.md)| Created user object | + **user** | [**User**](User.md)| Created user object | ### Return type @@ -55,31 +53,27 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: application/json + - **Accept**: Not defined # **create_users_with_array_input** -> create_users_with_array_input(body) +> create_users_with_array_input(user) Creates list of users with given input array - - ### Example ```ruby # load the gem require 'petstore' api_instance = Petstore::UserApi.new - -body = [Petstore::User.new] # Array | List of user object - +user = [Petstore::User.new] # Array | List of user object begin #Creates list of users with given input array - api_instance.create_users_with_array_input(body) + api_instance.create_users_with_array_input(user) rescue Petstore::ApiError => e puts "Exception when calling UserApi->create_users_with_array_input: #{e}" end @@ -89,7 +83,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Array<User>**](User.md)| List of user object | + **user** | [**Array<User>**](User.md)| List of user object | ### Return type @@ -102,30 +96,26 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Accept**: Not defined # **create_users_with_list_input** -> create_users_with_list_input(body) +> create_users_with_list_input(user) Creates list of users with given input array - - ### Example ```ruby # load the gem require 'petstore' api_instance = Petstore::UserApi.new - -body = [Petstore::User.new] # Array | List of user object - +user = [Petstore::User.new] # Array | List of user object begin #Creates list of users with given input array - api_instance.create_users_with_list_input(body) + api_instance.create_users_with_list_input(user) rescue Petstore::ApiError => e puts "Exception when calling UserApi->create_users_with_list_input: #{e}" end @@ -135,7 +125,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Array<User>**](User.md)| List of user object | + **user** | [**Array<User>**](User.md)| List of user object | ### Return type @@ -148,7 +138,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Accept**: Not defined @@ -165,10 +155,8 @@ This can only be done by the logged in user. require 'petstore' api_instance = Petstore::UserApi.new - username = 'username_example' # String | The name that needs to be deleted - begin #Delete user api_instance.delete_user(username) @@ -194,7 +182,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Accept**: Not defined @@ -203,18 +191,14 @@ No authorization required Get user by user name - - ### Example ```ruby # load the gem require 'petstore' api_instance = Petstore::UserApi.new - username = 'username_example' # String | The name that needs to be fetched. Use user1 for testing. - begin #Get user by user name result = api_instance.get_user_by_name(username) @@ -250,20 +234,15 @@ No authorization required Logs user into the system - - ### Example ```ruby # load the gem require 'petstore' api_instance = Petstore::UserApi.new - username = 'username_example' # String | The user name for login - password = 'password_example' # String | The password for login in clear text - begin #Logs user into the system result = api_instance.login_user(username, password) @@ -300,8 +279,6 @@ No authorization required Logs out current logged in user session - - ### Example ```ruby # load the gem @@ -331,12 +308,12 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Accept**: Not defined # **update_user** -> update_user(username, body) +> update_user(username, user) Updated user @@ -348,15 +325,12 @@ This can only be done by the logged in user. require 'petstore' api_instance = Petstore::UserApi.new - username = 'username_example' # String | name that need to be deleted - -body = Petstore::User.new # User | Updated user object - +user = Petstore::User.new # User | Updated user object begin #Updated user - api_instance.update_user(username, body) + api_instance.update_user(username, user) rescue Petstore::ApiError => e puts "Exception when calling UserApi->update_user: #{e}" end @@ -367,7 +341,7 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **String**| name that need to be deleted | - **body** | [**User**](User.md)| Updated user object | + **user** | [**User**](User.md)| Updated user object | ### Return type @@ -379,8 +353,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: application/json + - **Accept**: Not defined diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 3fdda9d94deb..51622b9d2bfa 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -24,10 +24,13 @@ require 'petstore/models/array_of_array_of_number_only' require 'petstore/models/array_of_number_only' require 'petstore/models/array_test' +require 'petstore/models/body4' require 'petstore/models/capitalization' +require 'petstore/models/cat' require 'petstore/models/category' require 'petstore/models/class_model' require 'petstore/models/client' +require 'petstore/models/dog' require 'petstore/models/enum_arrays' require 'petstore/models/enum_class' require 'petstore/models/enum_test' @@ -36,7 +39,7 @@ require 'petstore/models/list' require 'petstore/models/map_test' require 'petstore/models/mixed_properties_and_additional_properties_class' -require 'petstore/models/model_200_response' +require 'petstore/models/model200_response' require 'petstore/models/model_return' require 'petstore/models/name' require 'petstore/models/number_only' @@ -51,8 +54,6 @@ require 'petstore/models/special_model_name' require 'petstore/models/tag' require 'petstore/models/user' -require 'petstore/models/cat' -require 'petstore/models/dog' # APIs require 'petstore/api/another_fake_api' diff --git a/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb index 46538f3ecc79..dd84c7f1a01b 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb @@ -21,26 +21,26 @@ def initialize(api_client = ApiClient.default) end # To test special tags # To test special tags - # @param body client model + # @param client client model # @param [Hash] opts the optional parameters # @return [Client] - def test_special_tags(body, opts = {}) - data, _status_code, _headers = test_special_tags_with_http_info(body, opts) + def test_special_tags(client, opts = {}) + data, _status_code, _headers = test_special_tags_with_http_info(client, opts) data end # To test special tags # To test special tags - # @param body client model + # @param client client model # @param [Hash] opts the optional parameters # @return [Array<(Client, Fixnum, Hash)>] Client data, response status code and response headers - def test_special_tags_with_http_info(body, opts = {}) + def test_special_tags_with_http_info(client, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: AnotherFakeApi.test_special_tags ...' end - # verify the required parameter 'body' is set - if @api_client.config.client_side_validation && body.nil? - fail ArgumentError, "Missing the required parameter 'body' when calling AnotherFakeApi.test_special_tags" + # verify the required parameter 'client' is set + if @api_client.config.client_side_validation && client.nil? + fail ArgumentError, "Missing the required parameter 'client' when calling AnotherFakeApi.test_special_tags" end # resource path local_var_path = '/another-fake/dummy' @@ -52,14 +52,12 @@ def test_special_tags_with_http_info(body, opts = {}) header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) - # HTTP header 'Content-Type' - header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(body) + post_body = @api_client.object_to_http_body(client) auth_names = [] data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, :header_params => header_params, diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index 3bb14d1aacf9..d416003a183d 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -21,7 +21,7 @@ def initialize(api_client = ApiClient.default) end # Test serialization of outer boolean types # @param [Hash] opts the optional parameters - # @option opts [OuterBoolean] :body Input boolean as post body + # @option opts [BOOLEAN] :body Input boolean as post body # @return [OuterBoolean] def fake_outer_boolean_serialize(opts = {}) data, _status_code, _headers = fake_outer_boolean_serialize_with_http_info(opts) @@ -30,7 +30,7 @@ def fake_outer_boolean_serialize(opts = {}) # Test serialization of outer boolean types # @param [Hash] opts the optional parameters - # @option opts [OuterBoolean] :body Input boolean as post body + # @option opts [BOOLEAN] :body Input boolean as post body # @return [Array<(OuterBoolean, Fixnum, Hash)>] OuterBoolean data, response status code and response headers def fake_outer_boolean_serialize_with_http_info(opts = {}) if @api_client.config.debugging @@ -44,6 +44,10 @@ def fake_outer_boolean_serialize_with_http_info(opts = {}) # header parameters header_params = {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['*/*']) + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} @@ -65,7 +69,7 @@ def fake_outer_boolean_serialize_with_http_info(opts = {}) end # Test serialization of object with outer number type # @param [Hash] opts the optional parameters - # @option opts [OuterComposite] :body Input composite as post body + # @option opts [OuterComposite] :outer_composite Input composite as post body # @return [OuterComposite] def fake_outer_composite_serialize(opts = {}) data, _status_code, _headers = fake_outer_composite_serialize_with_http_info(opts) @@ -74,7 +78,7 @@ def fake_outer_composite_serialize(opts = {}) # Test serialization of object with outer number type # @param [Hash] opts the optional parameters - # @option opts [OuterComposite] :body Input composite as post body + # @option opts [OuterComposite] :outer_composite Input composite as post body # @return [Array<(OuterComposite, Fixnum, Hash)>] OuterComposite data, response status code and response headers def fake_outer_composite_serialize_with_http_info(opts = {}) if @api_client.config.debugging @@ -88,12 +92,16 @@ def fake_outer_composite_serialize_with_http_info(opts = {}) # header parameters header_params = {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['*/*']) + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'outer_composite']) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, @@ -109,7 +117,7 @@ def fake_outer_composite_serialize_with_http_info(opts = {}) end # Test serialization of outer number types # @param [Hash] opts the optional parameters - # @option opts [OuterNumber] :body Input number as post body + # @option opts [Float] :body Input number as post body # @return [OuterNumber] def fake_outer_number_serialize(opts = {}) data, _status_code, _headers = fake_outer_number_serialize_with_http_info(opts) @@ -118,7 +126,7 @@ def fake_outer_number_serialize(opts = {}) # Test serialization of outer number types # @param [Hash] opts the optional parameters - # @option opts [OuterNumber] :body Input number as post body + # @option opts [Float] :body Input number as post body # @return [Array<(OuterNumber, Fixnum, Hash)>] OuterNumber data, response status code and response headers def fake_outer_number_serialize_with_http_info(opts = {}) if @api_client.config.debugging @@ -132,6 +140,10 @@ def fake_outer_number_serialize_with_http_info(opts = {}) # header parameters header_params = {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['*/*']) + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} @@ -153,7 +165,7 @@ def fake_outer_number_serialize_with_http_info(opts = {}) end # Test serialization of outer string types # @param [Hash] opts the optional parameters - # @option opts [OuterString] :body Input string as post body + # @option opts [String] :body Input string as post body # @return [OuterString] def fake_outer_string_serialize(opts = {}) data, _status_code, _headers = fake_outer_string_serialize_with_http_info(opts) @@ -162,7 +174,7 @@ def fake_outer_string_serialize(opts = {}) # Test serialization of outer string types # @param [Hash] opts the optional parameters - # @option opts [OuterString] :body Input string as post body + # @option opts [String] :body Input string as post body # @return [Array<(OuterString, Fixnum, Hash)>] OuterString data, response status code and response headers def fake_outer_string_serialize_with_http_info(opts = {}) if @api_client.config.debugging @@ -176,6 +188,10 @@ def fake_outer_string_serialize_with_http_info(opts = {}) # header parameters header_params = {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['*/*']) + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} @@ -197,26 +213,26 @@ def fake_outer_string_serialize_with_http_info(opts = {}) end # To test \"client\" model # To test \"client\" model - # @param body client model + # @param client client model # @param [Hash] opts the optional parameters # @return [Client] - def test_client_model(body, opts = {}) - data, _status_code, _headers = test_client_model_with_http_info(body, opts) + def test_client_model(client, opts = {}) + data, _status_code, _headers = test_client_model_with_http_info(client, opts) data end # To test \"client\" model # To test \"client\" model - # @param body client model + # @param client client model # @param [Hash] opts the optional parameters # @return [Array<(Client, Fixnum, Hash)>] Client data, response status code and response headers - def test_client_model_with_http_info(body, opts = {}) + def test_client_model_with_http_info(client, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: FakeApi.test_client_model ...' end - # verify the required parameter 'body' is set - if @api_client.config.client_side_validation && body.nil? - fail ArgumentError, "Missing the required parameter 'body' when calling FakeApi.test_client_model" + # verify the required parameter 'client' is set + if @api_client.config.client_side_validation && client.nil? + fail ArgumentError, "Missing the required parameter 'client' when calling FakeApi.test_client_model" end # resource path local_var_path = '/fake' @@ -228,14 +244,12 @@ def test_client_model_with_http_info(body, opts = {}) header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) - # HTTP header 'Content-Type' - header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(body) + post_body = @api_client.object_to_http_body(client) auth_names = [] data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, :header_params => header_params, @@ -261,7 +275,7 @@ def test_client_model_with_http_info(body, opts = {}) # @option opts [Integer] :int64 None # @option opts [Float] :float None # @option opts [String] :string None - # @option opts [String] :binary None + # @option opts [File] :binary None # @option opts [Date] :date None # @option opts [DateTime] :date_time None # @option opts [String] :password None @@ -284,7 +298,7 @@ def test_endpoint_parameters(number, double, pattern_without_delimiter, byte, op # @option opts [Integer] :int64 None # @option opts [Float] :float None # @option opts [String] :string None - # @option opts [String] :binary None + # @option opts [File] :binary None # @option opts [Date] :date None # @option opts [DateTime] :date_time None # @option opts [String] :password None @@ -322,10 +336,6 @@ def test_endpoint_parameters_with_http_info(number, double, pattern_without_deli if @api_client.config.client_side_validation && pattern_without_delimiter.nil? fail ArgumentError, "Missing the required parameter 'pattern_without_delimiter' when calling FakeApi.test_endpoint_parameters" end - if @api_client.config.client_side_validation && pattern_without_delimiter !~ Regexp.new(/^[A-Z].*/) - fail ArgumentError, "invalid value for 'pattern_without_delimiter' when calling FakeApi.test_endpoint_parameters, must conform to the pattern /^[A-Z].*/." - end - # verify the required parameter 'byte' is set if @api_client.config.client_side_validation && byte.nil? fail ArgumentError, "Missing the required parameter 'byte' when calling FakeApi.test_endpoint_parameters" @@ -350,10 +360,6 @@ def test_endpoint_parameters_with_http_info(number, double, pattern_without_deli fail ArgumentError, 'invalid value for "opts[:"float"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 987.6.' end - if @api_client.config.client_side_validation && !opts[:'string'].nil? && opts[:'string'] !~ Regexp.new(/[a-z]/i) - fail ArgumentError, "invalid value for 'opts[:\"string\"]' when calling FakeApi.test_endpoint_parameters, must conform to the pattern /[a-z]/i." - end - if @api_client.config.client_side_validation && !opts[:'password'].nil? && opts[:'password'].to_s.length > 64 fail ArgumentError, 'invalid value for "opts[:"password"]" when calling FakeApi.test_endpoint_parameters, the character length must be smaller than or equal to 64.' end @@ -370,10 +376,8 @@ def test_endpoint_parameters_with_http_info(number, double, pattern_without_deli # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) # HTTP header 'Content-Type' - header_params['Content-Type'] = @api_client.select_header_content_type(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) + header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} @@ -409,14 +413,14 @@ def test_endpoint_parameters_with_http_info(number, double, pattern_without_deli # To test enum parameters # To test enum parameters # @param [Hash] opts the optional parameters - # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) - # @option opts [String] :enum_form_string Form parameter enum test (string) (default to -efg) # @option opts [Array] :enum_header_string_array Header parameter enum test (string array) - # @option opts [String] :enum_header_string Header parameter enum test (string) (default to -efg) + # @option opts [String] :enum_header_string Header parameter enum test (string) # @option opts [Array] :enum_query_string_array Query parameter enum test (string array) - # @option opts [String] :enum_query_string Query parameter enum test (string) (default to -efg) + # @option opts [String] :enum_query_string Query parameter enum test (string) # @option opts [Integer] :enum_query_integer Query parameter enum test (double) # @option opts [Float] :enum_query_double Query parameter enum test (double) + # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) + # @option opts [String] :enum_form_string Form parameter enum test (string) # @return [nil] def test_enum_parameters(opts = {}) test_enum_parameters_with_http_info(opts) @@ -426,25 +430,19 @@ def test_enum_parameters(opts = {}) # To test enum parameters # To test enum parameters # @param [Hash] opts the optional parameters - # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) - # @option opts [String] :enum_form_string Form parameter enum test (string) # @option opts [Array] :enum_header_string_array Header parameter enum test (string array) # @option opts [String] :enum_header_string Header parameter enum test (string) # @option opts [Array] :enum_query_string_array Query parameter enum test (string array) # @option opts [String] :enum_query_string Query parameter enum test (string) # @option opts [Integer] :enum_query_integer Query parameter enum test (double) # @option opts [Float] :enum_query_double Query parameter enum test (double) + # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) + # @option opts [String] :enum_form_string Form parameter enum test (string) # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def test_enum_parameters_with_http_info(opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: FakeApi.test_enum_parameters ...' end - if @api_client.config.client_side_validation && opts[:'enum_form_string_array'] && !opts[:'enum_form_string_array'].all? { |item| ['>', '$'].include?(item) } - fail ArgumentError, 'invalid value for "enum_form_string_array", must include one of >, $' - end - if @api_client.config.client_side_validation && opts[:'enum_form_string'] && !['_abc', '-efg', '(xyz)'].include?(opts[:'enum_form_string']) - fail ArgumentError, 'invalid value for "enum_form_string", must be one of _abc, -efg, (xyz)' - end if @api_client.config.client_side_validation && opts[:'enum_header_string_array'] && !opts[:'enum_header_string_array'].all? { |item| ['>', '$'].include?(item) } fail ArgumentError, 'invalid value for "enum_header_string_array", must include one of >, $' end @@ -463,29 +461,33 @@ def test_enum_parameters_with_http_info(opts = {}) if @api_client.config.client_side_validation && opts[:'enum_query_double'] && !['1.1', '-1.2'].include?(opts[:'enum_query_double']) fail ArgumentError, 'invalid value for "enum_query_double", must be one of 1.1, -1.2' end + if @api_client.config.client_side_validation && opts[:'enum_form_string_array'] && !['>', '$'].include?(opts[:'enum_form_string_array']) + fail ArgumentError, 'invalid value for "enum_form_string_array", must be one of >, $' + end + if @api_client.config.client_side_validation && opts[:'enum_form_string'] && !['_abc', '-efg', '(xyz)'].include?(opts[:'enum_form_string']) + fail ArgumentError, 'invalid value for "enum_form_string", must be one of _abc, -efg, (xyz)' + end # resource path local_var_path = '/fake' # query parameters query_params = {} - query_params[:'enum_query_string_array'] = @api_client.build_collection_param(opts[:'enum_query_string_array'], :csv) if !opts[:'enum_query_string_array'].nil? + query_params[:'enum_query_string_array'] = @api_client.build_collection_param(opts[:'enum_query_string_array'], :multi) if !opts[:'enum_query_string_array'].nil? query_params[:'enum_query_string'] = opts[:'enum_query_string'] if !opts[:'enum_query_string'].nil? query_params[:'enum_query_integer'] = opts[:'enum_query_integer'] if !opts[:'enum_query_integer'].nil? + query_params[:'enum_query_double'] = opts[:'enum_query_double'] if !opts[:'enum_query_double'].nil? # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['*/*']) # HTTP header 'Content-Type' - header_params['Content-Type'] = @api_client.select_header_content_type(['*/*']) + header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) header_params[:'enum_header_string_array'] = @api_client.build_collection_param(opts[:'enum_header_string_array'], :csv) if !opts[:'enum_header_string_array'].nil? header_params[:'enum_header_string'] = opts[:'enum_header_string'] if !opts[:'enum_header_string'].nil? # form parameters form_params = {} - form_params['enum_form_string_array'] = @api_client.build_collection_param(opts[:'enum_form_string_array'], :csv) if !opts[:'enum_form_string_array'].nil? + form_params['enum_form_string_array'] = opts[:'enum_form_string_array'] if !opts[:'enum_form_string_array'].nil? form_params['enum_form_string'] = opts[:'enum_form_string'] if !opts[:'enum_form_string'].nil? - form_params['enum_query_double'] = opts[:'enum_query_double'] if !opts[:'enum_query_double'].nil? # http body (model) post_body = nil @@ -502,27 +504,25 @@ def test_enum_parameters_with_http_info(opts = {}) return data, status_code, headers end # test inline additionalProperties - # - # @param param request body + # @param unknown_base_type request body # @param [Hash] opts the optional parameters # @return [nil] - def test_inline_additional_properties(param, opts = {}) - test_inline_additional_properties_with_http_info(param, opts) + def test_inline_additional_properties(unknown_base_type, opts = {}) + test_inline_additional_properties_with_http_info(unknown_base_type, opts) nil end # test inline additionalProperties - # - # @param param request body + # @param unknown_base_type request body # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def test_inline_additional_properties_with_http_info(param, opts = {}) + def test_inline_additional_properties_with_http_info(unknown_base_type, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: FakeApi.test_inline_additional_properties ...' end - # verify the required parameter 'param' is set - if @api_client.config.client_side_validation && param.nil? - fail ArgumentError, "Missing the required parameter 'param' when calling FakeApi.test_inline_additional_properties" + # verify the required parameter 'unknown_base_type' is set + if @api_client.config.client_side_validation && unknown_base_type.nil? + fail ArgumentError, "Missing the required parameter 'unknown_base_type' when calling FakeApi.test_inline_additional_properties" end # resource path local_var_path = '/fake/inline-additionalProperties' @@ -539,7 +539,7 @@ def test_inline_additional_properties_with_http_info(param, opts = {}) form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(param) + post_body = @api_client.object_to_http_body(unknown_base_type) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, @@ -553,34 +553,22 @@ def test_inline_additional_properties_with_http_info(param, opts = {}) return data, status_code, headers end # test json serialization of form data - # - # @param param field1 - # @param param2 field2 # @param [Hash] opts the optional parameters + # @option opts [Body4] :body4 # @return [nil] - def test_json_form_data(param, param2, opts = {}) - test_json_form_data_with_http_info(param, param2, opts) + def test_json_form_data(opts = {}) + test_json_form_data_with_http_info(opts) nil end # test json serialization of form data - # - # @param param field1 - # @param param2 field2 # @param [Hash] opts the optional parameters + # @option opts [Body4] :body4 # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def test_json_form_data_with_http_info(param, param2, opts = {}) + def test_json_form_data_with_http_info(opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: FakeApi.test_json_form_data ...' end - # verify the required parameter 'param' is set - if @api_client.config.client_side_validation && param.nil? - fail ArgumentError, "Missing the required parameter 'param' when calling FakeApi.test_json_form_data" - end - # verify the required parameter 'param2' is set - if @api_client.config.client_side_validation && param2.nil? - fail ArgumentError, "Missing the required parameter 'param2' when calling FakeApi.test_json_form_data" - end # resource path local_var_path = '/fake/jsonFormData' @@ -594,11 +582,9 @@ def test_json_form_data_with_http_info(param, param2, opts = {}) # form parameters form_params = {} - form_params['param'] = param - form_params['param2'] = param2 # http body (model) - post_body = nil + post_body = @api_client.object_to_http_body(opts[:'body4']) auth_names = [] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb index a3df63096fea..4f05959e5b4c 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb @@ -21,26 +21,26 @@ def initialize(api_client = ApiClient.default) end # To test class name in snake case # To test class name in snake case - # @param body client model + # @param client client model # @param [Hash] opts the optional parameters # @return [Client] - def test_classname(body, opts = {}) - data, _status_code, _headers = test_classname_with_http_info(body, opts) + def test_classname(client, opts = {}) + data, _status_code, _headers = test_classname_with_http_info(client, opts) data end # To test class name in snake case # To test class name in snake case - # @param body client model + # @param client client model # @param [Hash] opts the optional parameters # @return [Array<(Client, Fixnum, Hash)>] Client data, response status code and response headers - def test_classname_with_http_info(body, opts = {}) + def test_classname_with_http_info(client, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: FakeClassnameTags123Api.test_classname ...' end - # verify the required parameter 'body' is set - if @api_client.config.client_side_validation && body.nil? - fail ArgumentError, "Missing the required parameter 'body' when calling FakeClassnameTags123Api.test_classname" + # verify the required parameter 'client' is set + if @api_client.config.client_side_validation && client.nil? + fail ArgumentError, "Missing the required parameter 'client' when calling FakeClassnameTags123Api.test_classname" end # resource path local_var_path = '/fake_classname_test' @@ -52,14 +52,12 @@ def test_classname_with_http_info(body, opts = {}) header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) - # HTTP header 'Content-Type' - header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(body) + post_body = @api_client.object_to_http_body(client) auth_names = ['api_key_query'] data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, :header_params => header_params, diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index b5dc877eae86..5888e86acd04 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -20,27 +20,25 @@ def initialize(api_client = ApiClient.default) @api_client = api_client end # Add a new pet to the store - # - # @param body Pet object that needs to be added to the store + # @param pet Pet object that needs to be added to the store # @param [Hash] opts the optional parameters # @return [nil] - def add_pet(body, opts = {}) - add_pet_with_http_info(body, opts) + def add_pet(pet, opts = {}) + add_pet_with_http_info(pet, opts) nil end # Add a new pet to the store - # - # @param body Pet object that needs to be added to the store + # @param pet Pet object that needs to be added to the store # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def add_pet_with_http_info(body, opts = {}) + def add_pet_with_http_info(pet, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: PetApi.add_pet ...' end - # verify the required parameter 'body' is set - if @api_client.config.client_side_validation && body.nil? - fail ArgumentError, "Missing the required parameter 'body' when calling PetApi.add_pet" + # verify the required parameter 'pet' is set + if @api_client.config.client_side_validation && pet.nil? + fail ArgumentError, "Missing the required parameter 'pet' when calling PetApi.add_pet" end # resource path local_var_path = '/pet' @@ -50,16 +48,12 @@ def add_pet_with_http_info(body, opts = {}) # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) - # HTTP header 'Content-Type' - header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(body) + post_body = @api_client.object_to_http_body(pet) auth_names = ['petstore_auth'] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, @@ -73,7 +67,6 @@ def add_pet_with_http_info(body, opts = {}) return data, status_code, headers end # Deletes a pet - # # @param pet_id Pet id to delete # @param [Hash] opts the optional parameters # @option opts [String] :api_key @@ -84,7 +77,6 @@ def delete_pet(pet_id, opts = {}) end # Deletes a pet - # # @param pet_id Pet id to delete # @param [Hash] opts the optional parameters # @option opts [String] :api_key @@ -105,8 +97,6 @@ def delete_pet_with_http_info(pet_id, opts = {}) # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) header_params[:'api_key'] = opts[:'api_key'] if !opts[:'api_key'].nil? # form parameters @@ -285,27 +275,25 @@ def get_pet_by_id_with_http_info(pet_id, opts = {}) return data, status_code, headers end # Update an existing pet - # - # @param body Pet object that needs to be added to the store + # @param pet Pet object that needs to be added to the store # @param [Hash] opts the optional parameters # @return [nil] - def update_pet(body, opts = {}) - update_pet_with_http_info(body, opts) + def update_pet(pet, opts = {}) + update_pet_with_http_info(pet, opts) nil end # Update an existing pet - # - # @param body Pet object that needs to be added to the store + # @param pet Pet object that needs to be added to the store # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def update_pet_with_http_info(body, opts = {}) + def update_pet_with_http_info(pet, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: PetApi.update_pet ...' end - # verify the required parameter 'body' is set - if @api_client.config.client_side_validation && body.nil? - fail ArgumentError, "Missing the required parameter 'body' when calling PetApi.update_pet" + # verify the required parameter 'pet' is set + if @api_client.config.client_side_validation && pet.nil? + fail ArgumentError, "Missing the required parameter 'pet' when calling PetApi.update_pet" end # resource path local_var_path = '/pet' @@ -315,16 +303,12 @@ def update_pet_with_http_info(body, opts = {}) # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) - # HTTP header 'Content-Type' - header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(body) + post_body = @api_client.object_to_http_body(pet) auth_names = ['petstore_auth'] data, status_code, headers = @api_client.call_api(:PUT, local_var_path, :header_params => header_params, @@ -338,7 +322,6 @@ def update_pet_with_http_info(body, opts = {}) return data, status_code, headers end # Updates a pet in the store with form data - # # @param pet_id ID of pet that needs to be updated # @param [Hash] opts the optional parameters # @option opts [String] :name Updated name of the pet @@ -350,7 +333,6 @@ def update_pet_with_form(pet_id, opts = {}) end # Updates a pet in the store with form data - # # @param pet_id ID of pet that needs to be updated # @param [Hash] opts the optional parameters # @option opts [String] :name Updated name of the pet @@ -372,8 +354,6 @@ def update_pet_with_form_with_http_info(pet_id, opts = {}) # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) @@ -397,7 +377,6 @@ def update_pet_with_form_with_http_info(pet_id, opts = {}) return data, status_code, headers end # uploads an image - # # @param pet_id ID of pet to update # @param [Hash] opts the optional parameters # @option opts [String] :additional_metadata Additional data to pass to server @@ -409,7 +388,6 @@ def upload_file(pet_id, opts = {}) end # uploads an image - # # @param pet_id ID of pet to update # @param [Hash] opts the optional parameters # @option opts [String] :additional_metadata Additional data to pass to server diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index 19de80a7a144..fbfcc61a21ac 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -50,8 +50,6 @@ def delete_order_with_http_info(order_id, opts = {}) # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -177,27 +175,25 @@ def get_order_by_id_with_http_info(order_id, opts = {}) return data, status_code, headers end # Place an order for a pet - # - # @param body order placed for purchasing the pet + # @param order order placed for purchasing the pet # @param [Hash] opts the optional parameters # @return [Order] - def place_order(body, opts = {}) - data, _status_code, _headers = place_order_with_http_info(body, opts) + def place_order(order, opts = {}) + data, _status_code, _headers = place_order_with_http_info(order, opts) data end # Place an order for a pet - # - # @param body order placed for purchasing the pet + # @param order order placed for purchasing the pet # @param [Hash] opts the optional parameters # @return [Array<(Order, Fixnum, Hash)>] Order data, response status code and response headers - def place_order_with_http_info(body, opts = {}) + def place_order_with_http_info(order, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: StoreApi.place_order ...' end - # verify the required parameter 'body' is set - if @api_client.config.client_side_validation && body.nil? - fail ArgumentError, "Missing the required parameter 'body' when calling StoreApi.place_order" + # verify the required parameter 'order' is set + if @api_client.config.client_side_validation && order.nil? + fail ArgumentError, "Missing the required parameter 'order' when calling StoreApi.place_order" end # resource path local_var_path = '/store/order' @@ -209,12 +205,14 @@ def place_order_with_http_info(body, opts = {}) header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(body) + post_body = @api_client.object_to_http_body(order) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index d1c9040cd3c1..ba6990002832 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -21,26 +21,26 @@ def initialize(api_client = ApiClient.default) end # Create user # This can only be done by the logged in user. - # @param body Created user object + # @param user Created user object # @param [Hash] opts the optional parameters # @return [nil] - def create_user(body, opts = {}) - create_user_with_http_info(body, opts) + def create_user(user, opts = {}) + create_user_with_http_info(user, opts) nil end # Create user # This can only be done by the logged in user. - # @param body Created user object + # @param user Created user object # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def create_user_with_http_info(body, opts = {}) + def create_user_with_http_info(user, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: UserApi.create_user ...' end - # verify the required parameter 'body' is set - if @api_client.config.client_side_validation && body.nil? - fail ArgumentError, "Missing the required parameter 'body' when calling UserApi.create_user" + # verify the required parameter 'user' is set + if @api_client.config.client_side_validation && user.nil? + fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.create_user" end # resource path local_var_path = '/user' @@ -50,14 +50,14 @@ def create_user_with_http_info(body, opts = {}) # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(body) + post_body = @api_client.object_to_http_body(user) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, @@ -71,27 +71,25 @@ def create_user_with_http_info(body, opts = {}) return data, status_code, headers end # Creates list of users with given input array - # - # @param body List of user object + # @param user List of user object # @param [Hash] opts the optional parameters # @return [nil] - def create_users_with_array_input(body, opts = {}) - create_users_with_array_input_with_http_info(body, opts) + def create_users_with_array_input(user, opts = {}) + create_users_with_array_input_with_http_info(user, opts) nil end # Creates list of users with given input array - # - # @param body List of user object + # @param user List of user object # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def create_users_with_array_input_with_http_info(body, opts = {}) + def create_users_with_array_input_with_http_info(user, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: UserApi.create_users_with_array_input ...' end - # verify the required parameter 'body' is set - if @api_client.config.client_side_validation && body.nil? - fail ArgumentError, "Missing the required parameter 'body' when calling UserApi.create_users_with_array_input" + # verify the required parameter 'user' is set + if @api_client.config.client_side_validation && user.nil? + fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.create_users_with_array_input" end # resource path local_var_path = '/user/createWithArray' @@ -101,14 +99,12 @@ def create_users_with_array_input_with_http_info(body, opts = {}) # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(body) + post_body = @api_client.object_to_http_body(user) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, @@ -122,27 +118,25 @@ def create_users_with_array_input_with_http_info(body, opts = {}) return data, status_code, headers end # Creates list of users with given input array - # - # @param body List of user object + # @param user List of user object # @param [Hash] opts the optional parameters # @return [nil] - def create_users_with_list_input(body, opts = {}) - create_users_with_list_input_with_http_info(body, opts) + def create_users_with_list_input(user, opts = {}) + create_users_with_list_input_with_http_info(user, opts) nil end # Creates list of users with given input array - # - # @param body List of user object + # @param user List of user object # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def create_users_with_list_input_with_http_info(body, opts = {}) + def create_users_with_list_input_with_http_info(user, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: UserApi.create_users_with_list_input ...' end - # verify the required parameter 'body' is set - if @api_client.config.client_side_validation && body.nil? - fail ArgumentError, "Missing the required parameter 'body' when calling UserApi.create_users_with_list_input" + # verify the required parameter 'user' is set + if @api_client.config.client_side_validation && user.nil? + fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.create_users_with_list_input" end # resource path local_var_path = '/user/createWithList' @@ -152,14 +146,12 @@ def create_users_with_list_input_with_http_info(body, opts = {}) # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(body) + post_body = @api_client.object_to_http_body(user) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, @@ -203,8 +195,6 @@ def delete_user_with_http_info(username, opts = {}) # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -224,7 +214,6 @@ def delete_user_with_http_info(username, opts = {}) return data, status_code, headers end # Get user by user name - # # @param username The name that needs to be fetched. Use user1 for testing. # @param [Hash] opts the optional parameters # @return [User] @@ -234,7 +223,6 @@ def get_user_by_name(username, opts = {}) end # Get user by user name - # # @param username The name that needs to be fetched. Use user1 for testing. # @param [Hash] opts the optional parameters # @return [Array<(User, Fixnum, Hash)>] User data, response status code and response headers @@ -276,7 +264,6 @@ def get_user_by_name_with_http_info(username, opts = {}) return data, status_code, headers end # Logs user into the system - # # @param username The user name for login # @param password The password for login in clear text # @param [Hash] opts the optional parameters @@ -287,7 +274,6 @@ def login_user(username, password, opts = {}) end # Logs user into the system - # # @param username The user name for login # @param password The password for login in clear text # @param [Hash] opts the optional parameters @@ -336,7 +322,6 @@ def login_user_with_http_info(username, password, opts = {}) return data, status_code, headers end # Logs out current logged in user session - # # @param [Hash] opts the optional parameters # @return [nil] def logout_user(opts = {}) @@ -345,7 +330,6 @@ def logout_user(opts = {}) end # Logs out current logged in user session - # # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def logout_user_with_http_info(opts = {}) @@ -360,8 +344,6 @@ def logout_user_with_http_info(opts = {}) # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -383,21 +365,21 @@ def logout_user_with_http_info(opts = {}) # Updated user # This can only be done by the logged in user. # @param username name that need to be deleted - # @param body Updated user object + # @param user Updated user object # @param [Hash] opts the optional parameters # @return [nil] - def update_user(username, body, opts = {}) - update_user_with_http_info(username, body, opts) + def update_user(username, user, opts = {}) + update_user_with_http_info(username, user, opts) nil end # Updated user # This can only be done by the logged in user. # @param username name that need to be deleted - # @param body Updated user object + # @param user Updated user object # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def update_user_with_http_info(username, body, opts = {}) + def update_user_with_http_info(username, user, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: UserApi.update_user ...' end @@ -405,9 +387,9 @@ def update_user_with_http_info(username, body, opts = {}) if @api_client.config.client_side_validation && username.nil? fail ArgumentError, "Missing the required parameter 'username' when calling UserApi.update_user" end - # verify the required parameter 'body' is set - if @api_client.config.client_side_validation && body.nil? - fail ArgumentError, "Missing the required parameter 'body' when calling UserApi.update_user" + # verify the required parameter 'user' is set + if @api_client.config.client_side_validation && user.nil? + fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.update_user" end # resource path local_var_path = '/user/{username}'.sub('{' + 'username' + '}', username.to_s) @@ -417,14 +399,14 @@ def update_user_with_http_info(username, body, opts = {}) # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} # http body (model) - post_body = @api_client.object_to_http_body(body) + post_body = @api_client.object_to_http_body(user) auth_names = [] data, status_code, headers = @api_client.call_api(:PUT, local_var_path, :header_params => header_params, diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index cda8832f73c6..7abc60e43e8e 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -129,7 +129,7 @@ class Configuration def initialize @scheme = 'http' - @host = 'petstore.swagger.io:80' + @host = 'petstore.swagger.io' @base_path = '/v2' @api_key = {} @api_key_prefix = {} diff --git a/samples/client/petstore/ruby/lib/petstore/models/body4.rb b/samples/client/petstore/ruby/lib/petstore/models/body4.rb new file mode 100644 index 000000000000..7c0387d9b371 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/body4.rb @@ -0,0 +1,204 @@ +=begin +#Swagger 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 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git +Swagger Codegen version: 3.0.0-SNAPSHOT + +=end + +require 'date' + +module Petstore + class Body4 + # field1 + attr_accessor :param + + # field2 + attr_accessor :param2 + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'param' => :'param', + :'param2' => :'param2' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'param' => :'String', + :'param2' => :'String' + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } + + if attributes.has_key?(:'param') + self.param = attributes[:'param'] + end + + if attributes.has_key?(:'param2') + self.param2 = attributes[:'param2'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + if @param.nil? + invalid_properties.push('invalid value for "param", param cannot be nil.') + end + + if @param2.nil? + invalid_properties.push('invalid value for "param2", param2 cannot be nil.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return false if @param.nil? + return false if @param2.nil? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + param == o.param && + param2 == o.param2 + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [param, param2].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb index 7511f129f992..3ae49edf31ab 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -16,6 +16,8 @@ module Petstore class EnumTest attr_accessor :enum_string + attr_accessor :enum_string_required + attr_accessor :enum_integer attr_accessor :enum_number @@ -48,6 +50,7 @@ def valid?(value) def self.attribute_map { :'enum_string' => :'enum_string', + :'enum_string_required' => :'enum_string_required', :'enum_integer' => :'enum_integer', :'enum_number' => :'enum_number', :'outer_enum' => :'outerEnum' @@ -58,6 +61,7 @@ def self.attribute_map def self.swagger_types { :'enum_string' => :'String', + :'enum_string_required' => :'String', :'enum_integer' => :'Integer', :'enum_number' => :'Float', :'outer_enum' => :'OuterEnum' @@ -76,6 +80,10 @@ def initialize(attributes = {}) self.enum_string = attributes[:'enum_string'] end + if attributes.has_key?(:'enum_string_required') + self.enum_string_required = attributes[:'enum_string_required'] + end + if attributes.has_key?(:'enum_integer') self.enum_integer = attributes[:'enum_integer'] end @@ -93,6 +101,10 @@ def initialize(attributes = {}) # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new + if @enum_string_required.nil? + invalid_properties.push('invalid value for "enum_string_required", enum_string_required cannot be nil.') + end + invalid_properties end @@ -101,6 +113,9 @@ def list_invalid_properties def valid? enum_string_validator = EnumAttributeValidator.new('String', ['UPPER', 'lower', '']) return false unless enum_string_validator.valid?(@enum_string) + return false if @enum_string_required.nil? + enum_string_required_validator = EnumAttributeValidator.new('String', ['UPPER', 'lower', '']) + return false unless enum_string_required_validator.valid?(@enum_string_required) enum_integer_validator = EnumAttributeValidator.new('Integer', ['1', '-1']) return false unless enum_integer_validator.valid?(@enum_integer) enum_number_validator = EnumAttributeValidator.new('Float', ['1.1', '-1.2']) @@ -118,6 +133,16 @@ def enum_string=(enum_string) @enum_string = enum_string end + # Custom attribute writer method checking allowed values (enum). + # @param [Object] enum_string_required Object to be assigned + def enum_string_required=(enum_string_required) + validator = EnumAttributeValidator.new('String', ['UPPER', 'lower', '']) + unless validator.valid?(enum_string_required) + fail ArgumentError, 'invalid value for "enum_string_required", must be one of #{validator.allowable_values}.' + end + @enum_string_required = enum_string_required + end + # Custom attribute writer method checking allowed values (enum). # @param [Object] enum_integer Object to be assigned def enum_integer=(enum_integer) @@ -144,6 +169,7 @@ def ==(o) return true if self.equal?(o) self.class == o.class && enum_string == o.enum_string && + enum_string_required == o.enum_string_required && enum_integer == o.enum_integer && enum_number == o.enum_number && outer_enum == o.outer_enum @@ -158,7 +184,7 @@ def eql?(o) # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash - [enum_string, enum_integer, enum_number, outer_enum].hash + [enum_string, enum_string_required, enum_integer, enum_number, outer_enum].hash end # Builds the object from hash diff --git a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb index b24d8e32a7c7..6792db0f602c 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb @@ -70,7 +70,7 @@ def self.swagger_types :'double' => :'Float', :'string' => :'String', :'byte' => :'String', - :'binary' => :'String', + :'binary' => :'File', :'date' => :'Date', :'date_time' => :'DateTime', :'uuid' => :'String', @@ -187,18 +187,10 @@ def list_invalid_properties invalid_properties.push('invalid value for "double", must be greater than or equal to 67.8.') end - if !@string.nil? && @string !~ Regexp.new(/[a-z]/i) - invalid_properties.push('invalid value for "string", must conform to the pattern /[a-z]/i.') - end - if @byte.nil? invalid_properties.push('invalid value for "byte", byte cannot be nil.') end - if @byte !~ Regexp.new(/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/) - invalid_properties.push('invalid value for "byte", must conform to the pattern /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.') - end - if @date.nil? invalid_properties.push('invalid value for "date", date cannot be nil.') end @@ -232,9 +224,7 @@ def valid? return false if !@float.nil? && @float < 54.3 return false if !@double.nil? && @double > 123.4 return false if !@double.nil? && @double < 67.8 - return false if !@string.nil? && @string !~ Regexp.new(/[a-z]/i) return false if @byte.nil? - return false if @byte !~ Regexp.new(/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/) return false if @date.nil? return false if @password.nil? return false if @password.to_s.length > 64 @@ -316,30 +306,6 @@ def double=(double) @double = double end - # Custom attribute writer method with validation - # @param [Object] string Value to be assigned - def string=(string) - if !string.nil? && string !~ Regexp.new(/[a-z]/i) - fail ArgumentError, 'invalid value for "string", must conform to the pattern /[a-z]/i.' - end - - @string = string - end - - # Custom attribute writer method with validation - # @param [Object] byte Value to be assigned - def byte=(byte) - if byte.nil? - fail ArgumentError, 'byte cannot be nil' - end - - if byte !~ Regexp.new(/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/) - fail ArgumentError, 'invalid value for "byte", must conform to the pattern /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.' - end - - @byte = byte - end - # Custom attribute writer method with validation # @param [Object] password Value to be assigned def password=(password) diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb b/samples/client/petstore/ruby/lib/petstore/models/model200_response.rb similarity index 100% rename from samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb rename to samples/client/petstore/ruby/lib/petstore/models/model200_response.rb diff --git a/samples/client/petstore/ruby/spec/models/additional_properties_class_spec.rb b/samples/client/petstore/ruby/spec/models/additional_properties_class_spec.rb index 4ce11c586e86..0e4c8bec34b4 100644 --- a/samples/client/petstore/ruby/spec/models/additional_properties_class_spec.rb +++ b/samples/client/petstore/ruby/spec/models/additional_properties_class_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -36,5 +32,16 @@ expect(@instance).to be_instance_of(Petstore::AdditionalPropertiesClass) end end -end + describe 'test attribute "map_property"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + describe 'test attribute "map_of_map_property"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby/spec/models/animal_farm_spec.rb b/samples/client/petstore/ruby/spec/models/animal_farm_spec.rb index 2c61cd1ff161..895781828d2f 100644 --- a/samples/client/petstore/ruby/spec/models/animal_farm_spec.rb +++ b/samples/client/petstore/ruby/spec/models/animal_farm_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -37,4 +33,3 @@ end end end - diff --git a/samples/client/petstore/ruby/spec/models/animal_spec.rb b/samples/client/petstore/ruby/spec/models/animal_spec.rb index e430a78f89bc..6b77f9af7286 100644 --- a/samples/client/petstore/ruby/spec/models/animal_spec.rb +++ b/samples/client/petstore/ruby/spec/models/animal_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,15 +34,14 @@ end describe 'test attribute "class_name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "color"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/api_response_spec.rb b/samples/client/petstore/ruby/spec/models/api_response_spec.rb index e5d8b77690c4..52b8420ad71b 100644 --- a/samples/client/petstore/ruby/spec/models/api_response_spec.rb +++ b/samples/client/petstore/ruby/spec/models/api_response_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,21 +34,20 @@ end describe 'test attribute "code"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "type"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "message"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/array_of_array_of_number_only_spec.rb b/samples/client/petstore/ruby/spec/models/array_of_array_of_number_only_spec.rb index a563fa3c0a22..35bad7d85970 100644 --- a/samples/client/petstore/ruby/spec/models/array_of_array_of_number_only_spec.rb +++ b/samples/client/petstore/ruby/spec/models/array_of_array_of_number_only_spec.rb @@ -1,23 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -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. +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -45,9 +34,8 @@ end describe 'test attribute "array_array_number"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/array_of_number_only_spec.rb b/samples/client/petstore/ruby/spec/models/array_of_number_only_spec.rb index dfdcb0fcc2b3..84d4104b8006 100644 --- a/samples/client/petstore/ruby/spec/models/array_of_number_only_spec.rb +++ b/samples/client/petstore/ruby/spec/models/array_of_number_only_spec.rb @@ -1,23 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -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. +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -45,9 +34,8 @@ end describe 'test attribute "array_number"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/array_test_spec.rb b/samples/client/petstore/ruby/spec/models/array_test_spec.rb index a2d0cd6c0a7c..a6a5fb998a9b 100644 --- a/samples/client/petstore/ruby/spec/models/array_test_spec.rb +++ b/samples/client/petstore/ruby/spec/models/array_test_spec.rb @@ -1,23 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -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. +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -43,5 +32,22 @@ expect(@instance).to be_instance_of(Petstore::ArrayTest) end end -end + describe 'test attribute "array_of_string"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + describe 'test attribute "array_array_of_integer"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "array_array_of_model"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby/spec/models/body4_spec.rb b/samples/client/petstore/ruby/spec/models/body4_spec.rb new file mode 100644 index 000000000000..6279cc32efb8 --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/body4_spec.rb @@ -0,0 +1,47 @@ +=begin +#Swagger 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 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git +Swagger Codegen version: 3.0.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Body4 +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'Body4' do + before do + # run before each test + @instance = Petstore::Body4.new + end + + after do + # run after each test + end + + describe 'test an instance of Body4' do + it 'should create an instance of Body4' do + expect(@instance).to be_instance_of(Petstore::Body4) + end + end + describe 'test attribute "param"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "param2"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby/spec/models/capitalization_spec.rb b/samples/client/petstore/ruby/spec/models/capitalization_spec.rb index 5b6e005294b2..bcaa85523bc6 100644 --- a/samples/client/petstore/ruby/spec/models/capitalization_spec.rb +++ b/samples/client/petstore/ruby/spec/models/capitalization_spec.rb @@ -6,6 +6,7 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -33,39 +34,38 @@ end describe 'test attribute "small_camel"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "capital_camel"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "small_snake"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "capital_snake"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "sca_eth_flow_points"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "att_name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/cat_spec.rb b/samples/client/petstore/ruby/spec/models/cat_spec.rb index abae2076e3d0..d01ff50499ad 100644 --- a/samples/client/petstore/ruby/spec/models/cat_spec.rb +++ b/samples/client/petstore/ruby/spec/models/cat_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,21 +34,20 @@ end describe 'test attribute "class_name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "color"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "declawed"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/category_spec.rb b/samples/client/petstore/ruby/spec/models/category_spec.rb index e838fc15b081..ab8adb3fdae6 100644 --- a/samples/client/petstore/ruby/spec/models/category_spec.rb +++ b/samples/client/petstore/ruby/spec/models/category_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,15 +34,14 @@ end describe 'test attribute "id"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/class_model_spec.rb b/samples/client/petstore/ruby/spec/models/class_model_spec.rb index 4c0802e5b49d..6e5998b54c23 100644 --- a/samples/client/petstore/ruby/spec/models/class_model_spec.rb +++ b/samples/client/petstore/ruby/spec/models/class_model_spec.rb @@ -6,6 +6,7 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -33,9 +34,8 @@ end describe 'test attribute "_class"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/client_spec.rb b/samples/client/petstore/ruby/spec/models/client_spec.rb index c1292b7d8d07..5d5766906338 100644 --- a/samples/client/petstore/ruby/spec/models/client_spec.rb +++ b/samples/client/petstore/ruby/spec/models/client_spec.rb @@ -6,18 +6,7 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -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. +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -45,9 +34,8 @@ end describe 'test attribute "client"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/dog_spec.rb b/samples/client/petstore/ruby/spec/models/dog_spec.rb index 4400fdd34148..32acf1084db4 100644 --- a/samples/client/petstore/ruby/spec/models/dog_spec.rb +++ b/samples/client/petstore/ruby/spec/models/dog_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,21 +34,20 @@ end describe 'test attribute "class_name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "color"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "breed"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/enum_arrays_spec.rb b/samples/client/petstore/ruby/spec/models/enum_arrays_spec.rb index 4caf2a9f5efb..17ac2e5e37f5 100644 --- a/samples/client/petstore/ruby/spec/models/enum_arrays_spec.rb +++ b/samples/client/petstore/ruby/spec/models/enum_arrays_spec.rb @@ -6,18 +6,7 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -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. +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -43,25 +32,24 @@ expect(@instance).to be_instance_of(Petstore::EnumArrays) end end - describe 'test attribute "array_enum"' do + describe 'test attribute "just_symbol"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers - #validator = Petstore::EnumTest::EnumAttributeValidator.new('Array', []) - #validator.allowable_values.each do |value| - # expect { @instance.array_enum = value }.not_to raise_error - #end + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', [">=", "$"]) + # validator.allowable_values.each do |value| + # expect { @instance.just_symbol = value }.not_to raise_error + # end end end - describe 'test attribute "array_array_enum"' do + describe 'test attribute "array_enum"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers - #validator = Petstore::EnumTest::EnumAttributeValidator.new('Array>', []) - #validator.allowable_values.each do |value| - # expect { @instance.array_array_enum = value }.not_to raise_error - #end + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Array', ["fish", "crab"]) + # validator.allowable_values.each do |value| + # expect { @instance.array_enum = value }.not_to raise_error + # end end end end - diff --git a/samples/client/petstore/ruby/spec/models/enum_class_spec.rb b/samples/client/petstore/ruby/spec/models/enum_class_spec.rb index 8c78ce9e2664..3c4caca91762 100644 --- a/samples/client/petstore/ruby/spec/models/enum_class_spec.rb +++ b/samples/client/petstore/ruby/spec/models/enum_class_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -37,4 +33,3 @@ end end end - diff --git a/samples/client/petstore/ruby/spec/models/enum_test_spec.rb b/samples/client/petstore/ruby/spec/models/enum_test_spec.rb index f082b04e92b7..6b4b966a6a53 100644 --- a/samples/client/petstore/ruby/spec/models/enum_test_spec.rb +++ b/samples/client/petstore/ruby/spec/models/enum_test_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,30 +34,48 @@ end describe 'test attribute "enum_string"' do it 'should work' do - validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["UPPER", "lower"]) - validator.allowable_values.each do |value| - expect { @instance.enum_string = value }.not_to raise_error - end + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) + # validator.allowable_values.each do |value| + # expect { @instance.enum_string = value }.not_to raise_error + # end + end + end + + describe 'test attribute "enum_string_required"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) + # validator.allowable_values.each do |value| + # expect { @instance.enum_string_required = value }.not_to raise_error + # end end end describe 'test attribute "enum_integer"' do it 'should work' do - validator = Petstore::EnumTest::EnumAttributeValidator.new('Integer', ["1", "-1"]) - validator.allowable_values.each do |value| - expect { @instance.enum_integer = value }.not_to raise_error - end + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Integer', ["1", "-1"]) + # validator.allowable_values.each do |value| + # expect { @instance.enum_integer = value }.not_to raise_error + # end end end describe 'test attribute "enum_number"' do it 'should work' do - validator = Petstore::EnumTest::EnumAttributeValidator.new('Float', ["1.1", "-1.2"]) - validator.allowable_values.each do |value| - expect { @instance.enum_number = value }.not_to raise_error - end + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Float', ["1.1", "-1.2"]) + # validator.allowable_values.each do |value| + # expect { @instance.enum_number = value }.not_to raise_error + # end end end -end + describe 'test attribute "outer_enum"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end +end diff --git a/samples/client/petstore/ruby/spec/models/format_test_spec.rb b/samples/client/petstore/ruby/spec/models/format_test_spec.rb index 67bb3d7e941b..2fee049ec965 100644 --- a/samples/client/petstore/ruby/spec/models/format_test_spec.rb +++ b/samples/client/petstore/ruby/spec/models/format_test_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,81 +34,80 @@ end describe 'test attribute "integer"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "int32"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "int64"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "number"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "float"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "double"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "string"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "byte"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "binary"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "date"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "date_time"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "uuid"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "password"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/has_only_read_only_spec.rb b/samples/client/petstore/ruby/spec/models/has_only_read_only_spec.rb index dcc431c4f91b..9d84c9a07cd0 100644 --- a/samples/client/petstore/ruby/spec/models/has_only_read_only_spec.rb +++ b/samples/client/petstore/ruby/spec/models/has_only_read_only_spec.rb @@ -1,23 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -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. +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -45,15 +34,14 @@ end describe 'test attribute "bar"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "foo"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/list_spec.rb b/samples/client/petstore/ruby/spec/models/list_spec.rb index 694757b2f1c8..68bb5ae294d6 100644 --- a/samples/client/petstore/ruby/spec/models/list_spec.rb +++ b/samples/client/petstore/ruby/spec/models/list_spec.rb @@ -6,18 +6,7 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -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. +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -45,9 +34,8 @@ end describe 'test attribute "_123_list"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/map_test_spec.rb b/samples/client/petstore/ruby/spec/models/map_test_spec.rb index 408c8520dc2f..1735496e090f 100644 --- a/samples/client/petstore/ruby/spec/models/map_test_spec.rb +++ b/samples/client/petstore/ruby/spec/models/map_test_spec.rb @@ -1,23 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -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. +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -45,27 +34,18 @@ end describe 'test attribute "map_map_of_string"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers - end - end - - describe 'test attribute "map_map_of_enum"' do - it 'should work' do - validator = Petstore::EnumTest::EnumAttributeValidator.new('Hash>', []) - validator.allowable_values.each do |value| - expect { @instance.map_map_of_enum = value }.not_to raise_error - end + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "map_of_enum_string"' do it 'should work' do - validator = Petstore::EnumTest::EnumAttributeValidator.new('Hash', []) - validator.allowable_values.each do |value| - expect { @instance.map_of_enum_string = value }.not_to raise_error - end + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Hash', ["UPPER", "lower"]) + # validator.allowable_values.each do |value| + # expect { @instance.map_of_enum_string = value }.not_to raise_error + # end end end end - diff --git a/samples/client/petstore/ruby/spec/models/mixed_properties_and_additional_properties_class_spec.rb b/samples/client/petstore/ruby/spec/models/mixed_properties_and_additional_properties_class_spec.rb index b65744526e38..510fc0825fac 100644 --- a/samples/client/petstore/ruby/spec/models/mixed_properties_and_additional_properties_class_spec.rb +++ b/samples/client/petstore/ruby/spec/models/mixed_properties_and_additional_properties_class_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,15 +34,20 @@ end describe 'test attribute "uuid"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "date_time"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end -end + describe 'test attribute "map"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end +end diff --git a/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb b/samples/client/petstore/ruby/spec/models/model200_response_spec.rb similarity index 61% rename from samples/client/petstore/ruby/spec/models/model_200_response_spec.rb rename to samples/client/petstore/ruby/spec/models/model200_response_spec.rb index 889e44ac23f3..0a72f1cd7a51 100644 --- a/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb +++ b/samples/client/petstore/ruby/spec/models/model200_response_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,9 +34,14 @@ end describe 'test attribute "name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end -end + describe 'test attribute "_class"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end +end diff --git a/samples/client/petstore/ruby/spec/models/model_return_spec.rb b/samples/client/petstore/ruby/spec/models/model_return_spec.rb index 9ad2cace28f8..9f0cce65e397 100644 --- a/samples/client/petstore/ruby/spec/models/model_return_spec.rb +++ b/samples/client/petstore/ruby/spec/models/model_return_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,9 +34,8 @@ end describe 'test attribute "_return"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/name_spec.rb b/samples/client/petstore/ruby/spec/models/name_spec.rb index 70312a80c6a2..c39527e14b26 100644 --- a/samples/client/petstore/ruby/spec/models/name_spec.rb +++ b/samples/client/petstore/ruby/spec/models/name_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,27 +34,26 @@ end describe 'test attribute "name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "snake_case"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "property"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "_123_number"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/number_only_spec.rb b/samples/client/petstore/ruby/spec/models/number_only_spec.rb index f99f93e5cb2f..6aeeb6ca3271 100644 --- a/samples/client/petstore/ruby/spec/models/number_only_spec.rb +++ b/samples/client/petstore/ruby/spec/models/number_only_spec.rb @@ -1,23 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -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. +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -45,9 +34,8 @@ end describe 'test attribute "just_number"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/order_spec.rb b/samples/client/petstore/ruby/spec/models/order_spec.rb index 7e7acc2c3180..8f81f7a766e5 100644 --- a/samples/client/petstore/ruby/spec/models/order_spec.rb +++ b/samples/client/petstore/ruby/spec/models/order_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,42 +34,42 @@ end describe 'test attribute "id"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "pet_id"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "quantity"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "ship_date"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "status"' do it 'should work' do - validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["placed", "approved", "delivered"]) - validator.allowable_values.each do |value| - expect { @instance.status = value }.not_to raise_error - end + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["placed", "approved", "delivered"]) + # validator.allowable_values.each do |value| + # expect { @instance.status = value }.not_to raise_error + # end end end describe 'test attribute "complete"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/outer_boolean_spec.rb b/samples/client/petstore/ruby/spec/models/outer_boolean_spec.rb index 338738699eb8..174091474d06 100644 --- a/samples/client/petstore/ruby/spec/models/outer_boolean_spec.rb +++ b/samples/client/petstore/ruby/spec/models/outer_boolean_spec.rb @@ -6,6 +6,7 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -32,4 +33,3 @@ end end end - diff --git a/samples/client/petstore/ruby/spec/models/outer_composite_spec.rb b/samples/client/petstore/ruby/spec/models/outer_composite_spec.rb index bfa686760fcf..d5dce679bcf4 100644 --- a/samples/client/petstore/ruby/spec/models/outer_composite_spec.rb +++ b/samples/client/petstore/ruby/spec/models/outer_composite_spec.rb @@ -6,6 +6,7 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -33,21 +34,20 @@ end describe 'test attribute "my_number"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "my_string"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "my_boolean"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/outer_enum_spec.rb b/samples/client/petstore/ruby/spec/models/outer_enum_spec.rb index 9aca89bf192b..08f34bc4080c 100644 --- a/samples/client/petstore/ruby/spec/models/outer_enum_spec.rb +++ b/samples/client/petstore/ruby/spec/models/outer_enum_spec.rb @@ -6,6 +6,7 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -32,4 +33,3 @@ end end end - diff --git a/samples/client/petstore/ruby/spec/models/outer_number_spec.rb b/samples/client/petstore/ruby/spec/models/outer_number_spec.rb index a09a9f9d9da5..381860d9081d 100644 --- a/samples/client/petstore/ruby/spec/models/outer_number_spec.rb +++ b/samples/client/petstore/ruby/spec/models/outer_number_spec.rb @@ -6,6 +6,7 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -32,4 +33,3 @@ end end end - diff --git a/samples/client/petstore/ruby/spec/models/outer_string_spec.rb b/samples/client/petstore/ruby/spec/models/outer_string_spec.rb index d0be4816f2b7..e3dacb015c0d 100644 --- a/samples/client/petstore/ruby/spec/models/outer_string_spec.rb +++ b/samples/client/petstore/ruby/spec/models/outer_string_spec.rb @@ -6,6 +6,7 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -32,4 +33,3 @@ end end end - diff --git a/samples/client/petstore/ruby/spec/models/pet_spec.rb b/samples/client/petstore/ruby/spec/models/pet_spec.rb index 2d539ef5a397..9f7beebffe64 100644 --- a/samples/client/petstore/ruby/spec/models/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/models/pet_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,42 +34,42 @@ end describe 'test attribute "id"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "category"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "photo_urls"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "tags"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "status"' do it 'should work' do - validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["available", "pending", "sold"]) - validator.allowable_values.each do |value| - expect { @instance.status = value }.not_to raise_error - end + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + # validator.allowable_values.each do |value| + # expect { @instance.status = value }.not_to raise_error + # end end end end - diff --git a/samples/client/petstore/ruby/spec/models/read_only_first_spec.rb b/samples/client/petstore/ruby/spec/models/read_only_first_spec.rb index a6a65af4cf72..d3c18880b6fc 100644 --- a/samples/client/petstore/ruby/spec/models/read_only_first_spec.rb +++ b/samples/client/petstore/ruby/spec/models/read_only_first_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,15 +34,14 @@ end describe 'test attribute "bar"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "baz"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb b/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb index 351048050d81..10ae62410016 100644 --- a/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb +++ b/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,9 +34,8 @@ end describe 'test attribute "special_property_name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/tag_spec.rb b/samples/client/petstore/ruby/spec/models/tag_spec.rb index 2d0338fb466b..f8f824471ff9 100644 --- a/samples/client/petstore/ruby/spec/models/tag_spec.rb +++ b/samples/client/petstore/ruby/spec/models/tag_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,15 +34,14 @@ end describe 'test attribute "id"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/models/user_spec.rb b/samples/client/petstore/ruby/spec/models/user_spec.rb index 0b3035d6c75d..c47ad3967d51 100644 --- a/samples/client/petstore/ruby/spec/models/user_spec.rb +++ b/samples/client/petstore/ruby/spec/models/user_spec.rb @@ -1,16 +1,12 @@ =begin -Swagger Petstore +#Swagger 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: \" \\ +#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 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ +Swagger Codegen version: 3.0.0-SNAPSHOT =end @@ -38,51 +34,50 @@ end describe 'test attribute "id"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "username"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "first_name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "last_name"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "email"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "password"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "phone"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "user_status"' do it 'should work' do - # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end - diff --git a/samples/client/petstore/ruby/spec/store_spec.rb b/samples/client/petstore/ruby/spec/store_spec.rb index cdcaedfe44d4..a45f414544f1 100644 --- a/samples/client/petstore/ruby/spec/store_spec.rb +++ b/samples/client/petstore/ruby/spec/store_spec.rb @@ -14,7 +14,7 @@ @api.delete_order(@order_id) end - it "should featch the inventory" do + it "should fetch the inventory" do result = @api.get_inventory expect(result).to be_a(Hash) expect(result).not_to be_empty @@ -26,7 +26,7 @@ # mark as pending since original petstore does not return object # will re-enable this after updating the petstore server - xit "should featch the inventory in object" do + xit "should fetch the inventory in object" do result = @api.get_inventory_in_object expect(result).to be_a(Hash) expect(result).not_to be_empty diff --git a/samples/client/petstore/rust/docs/UserApi.md b/samples/client/petstore/rust/docs/UserApi.md index 80ae627c3b4d..6ccc9b08f366 100644 --- a/samples/client/petstore/rust/docs/UserApi.md +++ b/samples/client/petstore/rust/docs/UserApi.md @@ -132,7 +132,7 @@ Get user by user name Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | ### Return type diff --git a/samples/client/petstore/rust/src/apis/configuration.rs b/samples/client/petstore/rust/src/apis/configuration.rs index a5d8db713f0b..e501db7b6a97 100644 --- a/samples/client/petstore/rust/src/apis/configuration.rs +++ b/samples/client/petstore/rust/src/apis/configuration.rs @@ -9,11 +9,23 @@ */ use hyper; +use std::collections::HashMap; pub struct Configuration { pub base_path: String, pub user_agent: Option, pub client: hyper::client::Client, + pub basic_auth: Option, + pub oauth_access_token: Option, + pub api_key: Option, + // TODO: take an oauth2 token source, similar to the go one +} + +pub type BasicAuth = (String, Option); + +pub struct ApiKey { + pub prefix: Option, + pub key: String, } impl Configuration { @@ -22,6 +34,9 @@ impl Configuration { base_path: "http://petstore.swagger.io/v2".to_owned(), user_agent: Some("Swagger-Codegen/1.0.0/rust".to_owned()), client: client, + basic_auth: None, + oauth_access_token: None, + api_key: None, } } } diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs index 315ffeec112c..41199bc61caf 100644 --- a/samples/client/petstore/rust/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/src/apis/pet_api.rs @@ -11,6 +11,7 @@ use std::rc::Rc; use std::borrow::Borrow; use std::borrow::Cow; +use std::collections::HashMap; use hyper; use serde_json; @@ -49,22 +50,44 @@ implPetApi for PetApiClient { fn add_pet(&self, body: ::models::Pet) -> Box>> { let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut auth_headers = HashMap::::new(); + let mut auth_query = HashMap::::new(); + if let Some(ref token) = configuration.oauth_access_token { + let auth = hyper::header::Authorization( + hyper::header::Bearer { + token: token.to_owned(), + } + ); + auth_headers.insert("Authorization".to_owned(), auth.to_string()); + }; let method = hyper::Method::Post; - let uri_str = format!("{}/pet", configuration.base_path); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + for (key, val) in &auth_query { + query.append_pair(key, val); + } + query.finish() + }; + let uri_str = format!("{}/pet?{}", configuration.base_path, query_string); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + for (key, val) in auth_headers { + req.headers_mut().set_raw(key, val); + } + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -94,16 +117,34 @@ implPetApi for PetApiClient { fn delete_pet(&self, pet_id: i64, api_key: &str) -> Box>> { let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut auth_headers = HashMap::::new(); + let mut auth_query = HashMap::::new(); + if let Some(ref token) = configuration.oauth_access_token { + let auth = hyper::header::Authorization( + hyper::header::Bearer { + token: token.to_owned(), + } + ); + auth_headers.insert("Authorization".to_owned(), auth.to_string()); + }; let method = hyper::Method::Delete; - let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + for (key, val) in &auth_query { + query.append_pair(key, val); + } + query.finish() + }; + let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); @@ -114,6 +155,10 @@ implPetApi for PetApiClient { headers.set_raw("api_key", api_key); } + for (key, val) in auth_headers { + req.headers_mut().set_raw(key, val); + } + // send request Box::new( @@ -139,25 +184,45 @@ implPetApi for PetApiClient { fn find_pets_by_status(&self, status: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut auth_headers = HashMap::::new(); + let mut auth_query = HashMap::::new(); + if let Some(ref token) = configuration.oauth_access_token { + let auth = hyper::header::Authorization( + hyper::header::Bearer { + token: token.to_owned(), + } + ); + auth_headers.insert("Authorization".to_owned(), auth.to_string()); + }; let method = hyper::Method::Get; - let query = ::url::form_urlencoded::Serializer::new(String::new()) - .append_pair("status", &status.join(",").to_string()) - .finish(); - let uri_str = format!("{}/pet/findByStatus{}", configuration.base_path, query); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.append_pair("status", &status.join(",").to_string()); + for (key, val) in &auth_query { + query.append_pair(key, val); + } + query.finish() + }; + let uri_str = format!("{}/pet/findByStatus?{}", configuration.base_path, query_string); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + for (key, val) in auth_headers { + req.headers_mut().set_raw(key, val); + } + // send request Box::new( @@ -186,25 +251,45 @@ implPetApi for PetApiClient { fn find_pets_by_tags(&self, tags: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut auth_headers = HashMap::::new(); + let mut auth_query = HashMap::::new(); + if let Some(ref token) = configuration.oauth_access_token { + let auth = hyper::header::Authorization( + hyper::header::Bearer { + token: token.to_owned(), + } + ); + auth_headers.insert("Authorization".to_owned(), auth.to_string()); + }; let method = hyper::Method::Get; - let query = ::url::form_urlencoded::Serializer::new(String::new()) - .append_pair("tags", &tags.join(",").to_string()) - .finish(); - let uri_str = format!("{}/pet/findByTags{}", configuration.base_path, query); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.append_pair("tags", &tags.join(",").to_string()); + for (key, val) in &auth_query { + query.append_pair(key, val); + } + query.finish() + }; + let uri_str = format!("{}/pet/findByTags?{}", configuration.base_path, query_string); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + for (key, val) in auth_headers { + req.headers_mut().set_raw(key, val); + } + // send request Box::new( @@ -233,22 +318,44 @@ implPetApi for PetApiClient { fn get_pet_by_id(&self, pet_id: i64) -> Box>> { let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut auth_headers = HashMap::::new(); + let mut auth_query = HashMap::::new(); + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let val = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + auth_headers.insert("api_key".to_owned(), val); + }; let method = hyper::Method::Get; - let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + for (key, val) in &auth_query { + query.append_pair(key, val); + } + query.finish() + }; + let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + for (key, val) in auth_headers { + req.headers_mut().set_raw(key, val); + } + // send request Box::new( @@ -277,22 +384,44 @@ implPetApi for PetApiClient { fn update_pet(&self, body: ::models::Pet) -> Box>> { let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut auth_headers = HashMap::::new(); + let mut auth_query = HashMap::::new(); + if let Some(ref token) = configuration.oauth_access_token { + let auth = hyper::header::Authorization( + hyper::header::Bearer { + token: token.to_owned(), + } + ); + auth_headers.insert("Authorization".to_owned(), auth.to_string()); + }; let method = hyper::Method::Put; - let uri_str = format!("{}/pet", configuration.base_path); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + for (key, val) in &auth_query { + query.append_pair(key, val); + } + query.finish() + }; + let uri_str = format!("{}/pet?{}", configuration.base_path, query_string); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + for (key, val) in auth_headers { + req.headers_mut().set_raw(key, val); + } + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -322,22 +451,44 @@ implPetApi for PetApiClient { fn update_pet_with_form(&self, pet_id: i64, name: &str, status: &str) -> Box>> { let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut auth_headers = HashMap::::new(); + let mut auth_query = HashMap::::new(); + if let Some(ref token) = configuration.oauth_access_token { + let auth = hyper::header::Authorization( + hyper::header::Bearer { + token: token.to_owned(), + } + ); + auth_headers.insert("Authorization".to_owned(), auth.to_string()); + }; let method = hyper::Method::Post; - let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + for (key, val) in &auth_query { + query.append_pair(key, val); + } + query.finish() + }; + let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + for (key, val) in auth_headers { + req.headers_mut().set_raw(key, val); + } + // send request Box::new( @@ -363,22 +514,44 @@ implPetApi for PetApiClient { fn upload_file(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Box>> { let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut auth_headers = HashMap::::new(); + let mut auth_query = HashMap::::new(); + if let Some(ref token) = configuration.oauth_access_token { + let auth = hyper::header::Authorization( + hyper::header::Bearer { + token: token.to_owned(), + } + ); + auth_headers.insert("Authorization".to_owned(), auth.to_string()); + }; let method = hyper::Method::Post; - let uri_str = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + for (key, val) in &auth_query { + query.append_pair(key, val); + } + query.finish() + }; + let uri_str = format!("{}/pet/{petId}/uploadImage?{}", configuration.base_path, query_string, petId=pet_id); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + for (key, val) in auth_headers { + req.headers_mut().set_raw(key, val); + } + // send request Box::new( diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs index fe3c1d325c76..a4726b7b1392 100644 --- a/samples/client/petstore/rust/src/apis/store_api.rs +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -11,6 +11,7 @@ use std::rc::Rc; use std::borrow::Borrow; use std::borrow::Cow; +use std::collections::HashMap; use hyper; use serde_json; @@ -47,14 +48,19 @@ implStoreApi for StoreApiClient { let method = hyper::Method::Delete; - let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.finish() + }; + let uri_str = format!("{}/store/order/{orderId}?{}", configuration.base_path, query_string, orderId=order_id); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); @@ -62,6 +68,7 @@ implStoreApi for StoreApiClient { + // send request Box::new( configuration.client.request(req) @@ -86,22 +93,44 @@ implStoreApi for StoreApiClient { fn get_inventory(&self, ) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut auth_headers = HashMap::::new(); + let mut auth_query = HashMap::::new(); + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let val = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + auth_headers.insert("api_key".to_owned(), val); + }; let method = hyper::Method::Get; - let uri_str = format!("{}/store/inventory", configuration.base_path); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + for (key, val) in &auth_query { + query.append_pair(key, val); + } + query.finish() + }; + let uri_str = format!("{}/store/inventory?{}", configuration.base_path, query_string); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + for (key, val) in auth_headers { + req.headers_mut().set_raw(key, val); + } + // send request Box::new( @@ -132,14 +161,19 @@ implStoreApi for StoreApiClient { let method = hyper::Method::Get; - let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.finish() + }; + let uri_str = format!("{}/store/order/{orderId}?{}", configuration.base_path, query_string, orderId=order_id); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); @@ -147,6 +181,7 @@ implStoreApi for StoreApiClient { + // send request Box::new( configuration.client.request(req) @@ -176,20 +211,26 @@ implStoreApi for StoreApiClient { let method = hyper::Method::Post; - let uri_str = format!("{}/store/order", configuration.base_path); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.finish() + }; + let uri_str = format!("{}/store/order?{}", configuration.base_path, query_string); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs index c3c9f7d457e7..947932c5a702 100644 --- a/samples/client/petstore/rust/src/apis/user_api.rs +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -11,6 +11,7 @@ use std::rc::Rc; use std::borrow::Borrow; use std::borrow::Cow; +use std::collections::HashMap; use hyper; use serde_json; @@ -51,20 +52,26 @@ implUserApi for UserApiClient { let method = hyper::Method::Post; - let uri_str = format!("{}/user", configuration.base_path); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.finish() + }; + let uri_str = format!("{}/user?{}", configuration.base_path, query_string); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -96,20 +103,26 @@ implUserApi for UserApiClient { let method = hyper::Method::Post; - let uri_str = format!("{}/user/createWithArray", configuration.base_path); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.finish() + }; + let uri_str = format!("{}/user/createWithArray?{}", configuration.base_path, query_string); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -141,20 +154,26 @@ implUserApi for UserApiClient { let method = hyper::Method::Post; - let uri_str = format!("{}/user/createWithList", configuration.base_path); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.finish() + }; + let uri_str = format!("{}/user/createWithList?{}", configuration.base_path, query_string); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -186,14 +205,19 @@ implUserApi for UserApiClient { let method = hyper::Method::Delete; - let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.finish() + }; + let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); @@ -201,6 +225,7 @@ implUserApi for UserApiClient { + // send request Box::new( configuration.client.request(req) @@ -227,14 +252,19 @@ implUserApi for UserApiClient { let method = hyper::Method::Get; - let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.finish() + }; + let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); @@ -242,6 +272,7 @@ implUserApi for UserApiClient { + // send request Box::new( configuration.client.request(req) @@ -271,18 +302,21 @@ implUserApi for UserApiClient { let method = hyper::Method::Get; - let query = ::url::form_urlencoded::Serializer::new(String::new()) - .append_pair("username", &username.to_string()) - .append_pair("password", &password.to_string()) - .finish(); - let uri_str = format!("{}/user/login{}", configuration.base_path, query); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.append_pair("username", &username.to_string()); + query.append_pair("password", &password.to_string()); + query.finish() + }; + let uri_str = format!("{}/user/login?{}", configuration.base_path, query_string); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); @@ -290,6 +324,7 @@ implUserApi for UserApiClient { + // send request Box::new( configuration.client.request(req) @@ -319,14 +354,19 @@ implUserApi for UserApiClient { let method = hyper::Method::Get; - let uri_str = format!("{}/user/logout", configuration.base_path); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.finish() + }; + let uri_str = format!("{}/user/logout?{}", configuration.base_path, query_string); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); @@ -334,6 +374,7 @@ implUserApi for UserApiClient { + // send request Box::new( configuration.client.request(req) @@ -360,20 +401,26 @@ implUserApi for UserApiClient { let method = hyper::Method::Put; - let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.finish() + }; + let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username); - let uri = uri_str.parse(); // TODO(farcaller): handle error // if let Err(e) = uri { // return Box::new(futures::future::err(e)); // } - let mut req = hyper::Request::new(method, uri.unwrap()); + let mut uri: hyper::Uri = uri_str.parse().unwrap(); + + let mut req = hyper::Request::new(method, uri); if let Some(ref user_agent) = configuration.user_agent { req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone()))); } + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); diff --git a/samples/client/petstore/rust2/examples/server_lib/server.rs b/samples/client/petstore/rust2/examples/server_lib/server.rs deleted file mode 100644 index 17ed199a74ef..000000000000 --- a/samples/client/petstore/rust2/examples/server_lib/server.rs +++ /dev/null @@ -1,294 +0,0 @@ -//! Server implementation of petstore_api. - -#![allow(unused_imports)] - -use futures::{self, Future}; -use chrono; -use futures::Stream; -use std::collections::HashMap; -use std::io::Error; -use swagger; - -use petstore_api::{Api, ApiError, Context, - TestSpecialTagsResponse, - GetXmlFeaturesResponse, - PostPlainTextResponse, - PostXmlFeaturesResponse, - PutPlainTextResponse, - FakeOuterBooleanSerializeResponse, - FakeOuterCompositeSerializeResponse, - FakeOuterNumberSerializeResponse, - FakeOuterStringSerializeResponse, - TestClientModelResponse, - TestEndpointParametersResponse, - TestEnumParametersResponse, - TestJsonFormDataResponse, - TestClassnameResponse, - AddPetResponse, - DeletePetResponse, - FindPetsByStatusResponse, - FindPetsByTagsResponse, - GetPetByIdResponse, - UpdatePetResponse, - UpdatePetWithFormResponse, - UploadFileResponse, - DeleteOrderResponse, - GetInventoryResponse, - GetOrderByIdResponse, - PlaceOrderResponse, - CreateUserResponse, - CreateUsersWithArrayInputResponse, - CreateUsersWithListInputResponse, - DeleteUserResponse, - GetUserByNameResponse, - LoginUserResponse, - LogoutUserResponse, - UpdateUserResponse -}; -use petstore_api::models; - -#[derive(Copy, Clone)] -pub struct Server; - -impl Api for Server { - - /// To test special tags - fn test_special_tags(&self, body: models::Client, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("test_special_tags({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Get some XML - fn get_xml_features(&self, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("get_xml_features() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Post some plaintext - fn post_plain_text(&self, message: String, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("post_plain_text(\"{}\") - X-Span-ID: {:?}", message, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Post some xml - fn post_xml_features(&self, xml_object: models::XmlObject, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("post_xml_features({:?}) - X-Span-ID: {:?}", xml_object, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Put some optional plaintext - fn put_plain_text(&self, message: Option, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("put_plain_text({:?}) - X-Span-ID: {:?}", message, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - - fn fake_outer_boolean_serialize(&self, body: Option, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - - fn fake_outer_composite_serialize(&self, body: Option, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - - fn fake_outer_number_serialize(&self, body: Option, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - - fn fake_outer_string_serialize(&self, body: Option, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// To test \"client\" model - fn test_client_model(&self, body: models::Client, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("test_client_model({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("test_endpoint_parameters({}, {}, \"{}\", \"{:?}\", {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// To test enum parameters - fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("test_enum_parameters({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// test json serialization of form data - fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("test_json_form_data(\"{}\", \"{}\") - X-Span-ID: {:?}", param, param2, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// To test class name in snake case - fn test_classname(&self, body: models::Client, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("test_classname({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Add a new pet to the store - fn add_pet(&self, body: models::Pet, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("add_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Deletes a pet - fn delete_pet(&self, pet_id: i64, api_key: Option, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("delete_pet({}, {:?}) - X-Span-ID: {:?}", pet_id, api_key, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Finds Pets by status - fn find_pets_by_status(&self, status: &Vec, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("find_pets_by_status({:?}) - X-Span-ID: {:?}", status, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Finds Pets by tags - fn find_pets_by_tags(&self, tags: &Vec, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("find_pets_by_tags({:?}) - X-Span-ID: {:?}", tags, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Find pet by ID - fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("get_pet_by_id({}) - X-Span-ID: {:?}", pet_id, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Update an existing pet - fn update_pet(&self, body: models::Pet, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("update_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Updates a pet in the store with form data - fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("update_pet_with_form({}, {:?}, {:?}) - X-Span-ID: {:?}", pet_id, name, status, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// uploads an image - fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("upload_file({}, {:?}, ) - X-Span-ID: {:?}", pet_id, additional_metadata, context.x_span_id.unwrap_or(String::from("")).clone()); - let _ = file; //Suppresses unused param warning - Box::new(futures::failed("Generic failure".into())) - } - - /// Delete purchase order by ID - fn delete_order(&self, order_id: String, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("delete_order(\"{}\") - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Returns pet inventories by status - fn get_inventory(&self, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("get_inventory() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Find purchase order by ID - fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("get_order_by_id({}) - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Place an order for a pet - fn place_order(&self, body: models::Order, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("place_order({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Create user - fn create_user(&self, body: models::User, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("create_user({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Creates list of users with given input array - fn create_users_with_array_input(&self, body: &Vec, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("create_users_with_array_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Creates list of users with given input array - fn create_users_with_list_input(&self, body: &Vec, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("create_users_with_list_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Delete user - fn delete_user(&self, username: String, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("delete_user(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Get user by user name - fn get_user_by_name(&self, username: String, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("get_user_by_name(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Logs user into the system - fn login_user(&self, username: String, password: String, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("login_user(\"{}\", \"{}\") - X-Span-ID: {:?}", username, password, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Logs out current logged in user session - fn logout_user(&self, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("logout_user() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - - /// Updated user - fn update_user(&self, username: String, body: models::User, context: &Context) -> Box + Send> { - let context = context.clone(); - println!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, body, context.x_span_id.unwrap_or(String::from("")).clone()); - Box::new(futures::failed("Generic failure".into())) - } - -} diff --git a/samples/client/petstore/swift3/default/.gitignore b/samples/client/petstore/swift3/default/.gitignore index 5e5d5cebcf47..fc4e330f8fab 100644 --- a/samples/client/petstore/swift3/default/.gitignore +++ b/samples/client/petstore/swift3/default/.gitignore @@ -54,7 +54,7 @@ Carthage/Build # fastlane # -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift index f5a6b4779524..4b90cfc5b4e0 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -68,7 +68,7 @@ class APIHelper { } } .flatMap { $0 } - + if returnValues.isEmpty { return nil } return returnValues } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift index 2e100b1fdcd9..0aa321fd6593 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift @@ -38,7 +38,7 @@ open class AnotherFakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index dbe5c7ceb6ed..df303ecf8c81 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -34,7 +34,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -69,7 +69,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -100,7 +100,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -131,7 +131,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -166,7 +166,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -243,8 +243,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -363,8 +363,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, @@ -413,8 +413,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift index e0313d4b2a24..e9e41a3f98ed 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift @@ -39,7 +39,7 @@ open class FakeClassnameTags123API: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift index bc4369df7aee..cf28bec4c897 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift @@ -39,7 +39,7 @@ open class Fake_classname_tags123API: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 6de1f3366206..028e532fd8c7 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -37,7 +37,7 @@ open class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -75,8 +75,8 @@ open class PetAPI: APIBase { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey ] @@ -206,8 +206,8 @@ open class PetAPI: APIBase { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "status": status ]) @@ -327,8 +327,8 @@ open class PetAPI: APIBase { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "tags": tags ]) @@ -419,8 +419,8 @@ open class PetAPI: APIBase { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -454,7 +454,7 @@ open class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -500,8 +500,8 @@ open class PetAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -552,8 +552,8 @@ open class PetAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 7d99f10de0c7..e089b64b9b55 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -37,8 +37,8 @@ open class StoreAPI: APIBase { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -72,8 +72,8 @@ open class StoreAPI: APIBase { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -137,8 +137,8 @@ open class StoreAPI: APIBase { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -200,7 +200,7 @@ open class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index b5bd0d0677a9..0985efca952b 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -35,7 +35,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -67,7 +67,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -99,7 +99,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -133,8 +133,8 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -206,8 +206,8 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -244,8 +244,8 @@ open class UserAPI: APIBase { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "username": username, "password": password @@ -278,8 +278,8 @@ open class UserAPI: APIBase { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -316,7 +316,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 2b001505c235..863f618326d3 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -345,7 +345,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } @@ -373,4 +373,4 @@ fileprivate enum DownloadException : Error { case requestMissing case requestMissingPath case requestMissingURL -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Configuration.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Configuration.swift index c03a10b930c5..7f777932fe96 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Configuration.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Configuration.swift @@ -7,9 +7,9 @@ import Foundation open class Configuration { - - // This value is used to configure the date formatter that is used to serialize dates into JSON format. - // You must set it prior to encoding any dates, and it will only be read once. + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift index 6301896211fe..0acd7ca42faf 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -185,7 +185,7 @@ class Decoders { return .success(nil) } } - + static func decodeOptional(clazz: [T].Type, source: AnyObject?) -> Decoded<[T]?> where T: RawRepresentable { if let source = source as? [AnyObject] { var values = [T]() diff --git a/samples/client/petstore/swift3/default/git_push.sh b/samples/client/petstore/swift3/default/git_push.sh index ae01b182ae9e..160f6f213999 100644 --- a/samples/client/petstore/swift3/default/git_push.sh +++ b/samples/client/petstore/swift3/default/git_push.sh @@ -28,7 +28,7 @@ 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. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote diff --git a/samples/client/petstore/swift3/objcCompatible/.gitignore b/samples/client/petstore/swift3/objcCompatible/.gitignore index 5e5d5cebcf47..fc4e330f8fab 100644 --- a/samples/client/petstore/swift3/objcCompatible/.gitignore +++ b/samples/client/petstore/swift3/objcCompatible/.gitignore @@ -54,7 +54,7 @@ Carthage/Build # fastlane # -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIHelper.swift index f5a6b4779524..4b90cfc5b4e0 100644 --- a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -68,7 +68,7 @@ class APIHelper { } } .flatMap { $0 } - + if returnValues.isEmpty { return nil } return returnValues } diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift index 2e100b1fdcd9..0aa321fd6593 100644 --- a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift @@ -38,7 +38,7 @@ open class AnotherFakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index dbe5c7ceb6ed..df303ecf8c81 100644 --- a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -34,7 +34,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -69,7 +69,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -100,7 +100,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -131,7 +131,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -166,7 +166,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -243,8 +243,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -363,8 +363,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, @@ -413,8 +413,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift index e0313d4b2a24..e9e41a3f98ed 100644 --- a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift @@ -39,7 +39,7 @@ open class FakeClassnameTags123API: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 6de1f3366206..028e532fd8c7 100644 --- a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -37,7 +37,7 @@ open class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -75,8 +75,8 @@ open class PetAPI: APIBase { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey ] @@ -206,8 +206,8 @@ open class PetAPI: APIBase { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "status": status ]) @@ -327,8 +327,8 @@ open class PetAPI: APIBase { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "tags": tags ]) @@ -419,8 +419,8 @@ open class PetAPI: APIBase { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -454,7 +454,7 @@ open class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -500,8 +500,8 @@ open class PetAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -552,8 +552,8 @@ open class PetAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 7d99f10de0c7..e089b64b9b55 100644 --- a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -37,8 +37,8 @@ open class StoreAPI: APIBase { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -72,8 +72,8 @@ open class StoreAPI: APIBase { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -137,8 +137,8 @@ open class StoreAPI: APIBase { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -200,7 +200,7 @@ open class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index b5bd0d0677a9..0985efca952b 100644 --- a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -35,7 +35,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -67,7 +67,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -99,7 +99,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -133,8 +133,8 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -206,8 +206,8 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -244,8 +244,8 @@ open class UserAPI: APIBase { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "username": username, "password": password @@ -278,8 +278,8 @@ open class UserAPI: APIBase { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -316,7 +316,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 2b001505c235..863f618326d3 100644 --- a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -345,7 +345,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } @@ -373,4 +373,4 @@ fileprivate enum DownloadException : Error { case requestMissing case requestMissingPath case requestMissingURL -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Configuration.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Configuration.swift index c03a10b930c5..7f777932fe96 100644 --- a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Configuration.swift +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Configuration.swift @@ -7,9 +7,9 @@ import Foundation open class Configuration { - - // This value is used to configure the date formatter that is used to serialize dates into JSON format. - // You must set it prior to encoding any dates, and it will only be read once. + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models.swift index 6301896211fe..0acd7ca42faf 100644 --- a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models.swift @@ -185,7 +185,7 @@ class Decoders { return .success(nil) } } - + static func decodeOptional(clazz: [T].Type, source: AnyObject?) -> Decoded<[T]?> where T: RawRepresentable { if let source = source as? [AnyObject] { var values = [T]() diff --git a/samples/client/petstore/swift3/objcCompatible/git_push.sh b/samples/client/petstore/swift3/objcCompatible/git_push.sh index ae01b182ae9e..160f6f213999 100644 --- a/samples/client/petstore/swift3/objcCompatible/git_push.sh +++ b/samples/client/petstore/swift3/objcCompatible/git_push.sh @@ -28,7 +28,7 @@ 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. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote diff --git a/samples/client/petstore/swift3/promisekit/.gitignore b/samples/client/petstore/swift3/promisekit/.gitignore index 5e5d5cebcf47..fc4e330f8fab 100644 --- a/samples/client/petstore/swift3/promisekit/.gitignore +++ b/samples/client/petstore/swift3/promisekit/.gitignore @@ -54,7 +54,7 @@ Carthage/Build # fastlane # -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift index f5a6b4779524..4b90cfc5b4e0 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -68,7 +68,7 @@ class APIHelper { } } .flatMap { $0 } - + if returnValues.isEmpty { return nil } return returnValues } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift index 82e9b8fac649..b0c53c97e3c7 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift @@ -55,7 +55,7 @@ open class AnotherFakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 1e328450eb78..fbb2420e4a7e 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -50,7 +50,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -100,7 +100,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -146,7 +146,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -192,7 +192,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -243,7 +243,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -349,8 +349,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -492,8 +492,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, @@ -559,8 +559,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift index 37f48c0e719d..4529d8ec9c22 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift @@ -56,7 +56,7 @@ open class FakeClassnameTags123API: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 27aa7ad8684a..27578224d59b 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -54,7 +54,7 @@ open class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -109,8 +109,8 @@ open class PetAPI: APIBase { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey ] @@ -256,8 +256,8 @@ open class PetAPI: APIBase { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "status": status ]) @@ -393,8 +393,8 @@ open class PetAPI: APIBase { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "tags": tags ]) @@ -501,8 +501,8 @@ open class PetAPI: APIBase { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -552,7 +552,7 @@ open class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -616,8 +616,8 @@ open class PetAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -686,8 +686,8 @@ open class PetAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 4b47025d3f31..4d558989f827 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -54,8 +54,8 @@ open class StoreAPI: APIBase { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -104,8 +104,8 @@ open class StoreAPI: APIBase { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -185,8 +185,8 @@ open class StoreAPI: APIBase { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -264,7 +264,7 @@ open class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 577a8bef6d54..de74a9a0028c 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -52,7 +52,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -100,7 +100,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -148,7 +148,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -198,8 +198,8 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -287,8 +287,8 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -342,8 +342,8 @@ open class UserAPI: APIBase { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "username": username, "password": password @@ -391,8 +391,8 @@ open class UserAPI: APIBase { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -446,7 +446,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 2b001505c235..863f618326d3 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -345,7 +345,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } @@ -373,4 +373,4 @@ fileprivate enum DownloadException : Error { case requestMissing case requestMissingPath case requestMissingURL -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Configuration.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Configuration.swift index c03a10b930c5..7f777932fe96 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Configuration.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Configuration.swift @@ -7,9 +7,9 @@ import Foundation open class Configuration { - - // This value is used to configure the date formatter that is used to serialize dates into JSON format. - // You must set it prior to encoding any dates, and it will only be read once. + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift index 6301896211fe..0acd7ca42faf 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift @@ -185,7 +185,7 @@ class Decoders { return .success(nil) } } - + static func decodeOptional(clazz: [T].Type, source: AnyObject?) -> Decoded<[T]?> where T: RawRepresentable { if let source = source as? [AnyObject] { var values = [T]() diff --git a/samples/client/petstore/swift3/promisekit/git_push.sh b/samples/client/petstore/swift3/promisekit/git_push.sh index ae01b182ae9e..160f6f213999 100644 --- a/samples/client/petstore/swift3/promisekit/git_push.sh +++ b/samples/client/petstore/swift3/promisekit/git_push.sh @@ -28,7 +28,7 @@ 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. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote diff --git a/samples/client/petstore/swift3/rxswift/.gitignore b/samples/client/petstore/swift3/rxswift/.gitignore index 5e5d5cebcf47..fc4e330f8fab 100644 --- a/samples/client/petstore/swift3/rxswift/.gitignore +++ b/samples/client/petstore/swift3/rxswift/.gitignore @@ -54,7 +54,7 @@ Carthage/Build # fastlane # -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift index f5a6b4779524..4b90cfc5b4e0 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -68,7 +68,7 @@ class APIHelper { } } .flatMap { $0 } - + if returnValues.isEmpty { return nil } return returnValues } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift index b37257eb955b..fd794110daff 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift @@ -57,7 +57,7 @@ open class AnotherFakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index a372f52b955e..9d9ff3681574 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -52,7 +52,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -104,7 +104,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -152,7 +152,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -200,7 +200,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -253,7 +253,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -361,8 +361,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -506,8 +506,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, @@ -575,8 +575,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift index bbad2e38b9fb..945db96a6eb3 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift @@ -58,7 +58,7 @@ open class FakeClassnameTags123API: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 3733e2cb16fd..3d328b558708 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -56,7 +56,7 @@ open class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -113,8 +113,8 @@ open class PetAPI: APIBase { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey ] @@ -262,8 +262,8 @@ open class PetAPI: APIBase { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "status": status ]) @@ -401,8 +401,8 @@ open class PetAPI: APIBase { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "tags": tags ]) @@ -511,8 +511,8 @@ open class PetAPI: APIBase { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -564,7 +564,7 @@ open class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -630,8 +630,8 @@ open class PetAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -702,8 +702,8 @@ open class PetAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 29ed72ba9609..f20ef73f3bc7 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -56,8 +56,8 @@ open class StoreAPI: APIBase { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -108,8 +108,8 @@ open class StoreAPI: APIBase { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -191,8 +191,8 @@ open class StoreAPI: APIBase { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -272,7 +272,7 @@ open class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 65789ede6ef0..d4b6542513bc 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -54,7 +54,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -104,7 +104,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -154,7 +154,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -206,8 +206,8 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -297,8 +297,8 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -354,8 +354,8 @@ open class UserAPI: APIBase { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "username": username, "password": password @@ -405,8 +405,8 @@ open class UserAPI: APIBase { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -462,7 +462,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 2b001505c235..863f618326d3 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -345,7 +345,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } @@ -373,4 +373,4 @@ fileprivate enum DownloadException : Error { case requestMissing case requestMissingPath case requestMissingURL -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Configuration.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Configuration.swift index c03a10b930c5..7f777932fe96 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Configuration.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Configuration.swift @@ -7,9 +7,9 @@ import Foundation open class Configuration { - - // This value is used to configure the date formatter that is used to serialize dates into JSON format. - // You must set it prior to encoding any dates, and it will only be read once. + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift index 6301896211fe..0acd7ca42faf 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift @@ -185,7 +185,7 @@ class Decoders { return .success(nil) } } - + static func decodeOptional(clazz: [T].Type, source: AnyObject?) -> Decoded<[T]?> where T: RawRepresentable { if let source = source as? [AnyObject] { var values = [T]() diff --git a/samples/client/petstore/swift3/rxswift/git_push.sh b/samples/client/petstore/swift3/rxswift/git_push.sh index ae01b182ae9e..160f6f213999 100644 --- a/samples/client/petstore/swift3/rxswift/git_push.sh +++ b/samples/client/petstore/swift3/rxswift/git_push.sh @@ -28,7 +28,7 @@ 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. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote diff --git a/samples/client/petstore/swift3/unwraprequired/.gitignore b/samples/client/petstore/swift3/unwraprequired/.gitignore index 5e5d5cebcf47..fc4e330f8fab 100644 --- a/samples/client/petstore/swift3/unwraprequired/.gitignore +++ b/samples/client/petstore/swift3/unwraprequired/.gitignore @@ -54,7 +54,7 @@ Carthage/Build # fastlane # -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIHelper.swift index f5a6b4779524..4b90cfc5b4e0 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -68,7 +68,7 @@ class APIHelper { } } .flatMap { $0 } - + if returnValues.isEmpty { return nil } return returnValues } diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift index 2e100b1fdcd9..0aa321fd6593 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift @@ -38,7 +38,7 @@ open class AnotherFakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index dbe5c7ceb6ed..df303ecf8c81 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -34,7 +34,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -69,7 +69,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -100,7 +100,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -131,7 +131,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -166,7 +166,7 @@ open class FakeAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -243,8 +243,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -363,8 +363,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, @@ -413,8 +413,8 @@ open class FakeAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift index e0313d4b2a24..e9e41a3f98ed 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift @@ -39,7 +39,7 @@ open class FakeClassnameTags123API: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 6de1f3366206..028e532fd8c7 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -37,7 +37,7 @@ open class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -75,8 +75,8 @@ open class PetAPI: APIBase { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey ] @@ -206,8 +206,8 @@ open class PetAPI: APIBase { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "status": status ]) @@ -327,8 +327,8 @@ open class PetAPI: APIBase { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "tags": tags ]) @@ -419,8 +419,8 @@ open class PetAPI: APIBase { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -454,7 +454,7 @@ open class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -500,8 +500,8 @@ open class PetAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -552,8 +552,8 @@ open class PetAPI: APIBase { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 7d99f10de0c7..e089b64b9b55 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -37,8 +37,8 @@ open class StoreAPI: APIBase { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -72,8 +72,8 @@ open class StoreAPI: APIBase { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -137,8 +137,8 @@ open class StoreAPI: APIBase { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -200,7 +200,7 @@ open class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index b5bd0d0677a9..0985efca952b 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -35,7 +35,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -67,7 +67,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -99,7 +99,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -133,8 +133,8 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -206,8 +206,8 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -244,8 +244,8 @@ open class UserAPI: APIBase { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "username": username, "password": password @@ -278,8 +278,8 @@ open class UserAPI: APIBase { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -316,7 +316,7 @@ open class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() - let url = NSURLComponents(string: URLString) + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 2b001505c235..863f618326d3 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -345,7 +345,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } @@ -373,4 +373,4 @@ fileprivate enum DownloadException : Error { case requestMissing case requestMissingPath case requestMissingURL -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/Configuration.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/Configuration.swift index c03a10b930c5..7f777932fe96 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/Configuration.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/Configuration.swift @@ -7,9 +7,9 @@ import Foundation open class Configuration { - - // This value is used to configure the date formatter that is used to serialize dates into JSON format. - // You must set it prior to encoding any dates, and it will only be read once. + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/Models.swift index a9516c1434bf..892e7e4a79b2 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/Models.swift @@ -185,7 +185,7 @@ class Decoders { return .success(nil) } } - + static func decodeOptional(clazz: [T].Type, source: AnyObject?) -> Decoded<[T]?> where T: RawRepresentable { if let source = source as? [AnyObject] { var values = [T]() diff --git a/samples/client/petstore/swift3/unwraprequired/git_push.sh b/samples/client/petstore/swift3/unwraprequired/git_push.sh index ae01b182ae9e..160f6f213999 100644 --- a/samples/client/petstore/swift3/unwraprequired/git_push.sh +++ b/samples/client/petstore/swift3/unwraprequired/git_push.sh @@ -28,7 +28,7 @@ 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. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIHelper.swift index b612ff90921a..81e7286d6d40 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -6,12 +6,11 @@ import Foundation -class APIHelper { - static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { - var destination = [String:Any]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = value +public struct APIHelper { + public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + let destination = source.reduce(into: [String: Any]()) { (result, item) in + if let value = item.value { + result[item.key] = value } } @@ -21,45 +20,46 @@ class APIHelper { return destination } - static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { - var destination = [String:String]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = "\(value)" + public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + return source.reduce(into: [String: String]()) { (result, item) in + if let collection = item.value as? Array { + result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = "\(value)" } } - return destination } - static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { guard let source = source else { return nil } - var destination = [String:Any]() - let theTrue = NSNumber(value: true as Bool) - let theFalse = NSNumber(value: false as Bool) - for (key, value) in source { - switch value { - case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse: - destination[key] = "\(value as! Bool)" as Any? + + return source.reduce(into: [String: Any](), { (result, item) in + switch item.value { + case let x as Bool: + result[item.key] = x.description default: - destination[key] = value + result[item.key] = item.value } - } - return destination + }) } - static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { - let returnValues = values - .filter { $0.1 != nil } - .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in - URLQueryItem(name: item._key, value:"\(item._value!)") + public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in + if let collection = item.value as? Array { + let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + result.append(URLQueryItem(name: item.key, value: value)) + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: "\(value)")) } - if returnValues.count == 0 { + } + + if destination.isEmpty { return nil } - return returnValues + return destination } - } + diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift index 1d439bf00892..63377bce9981 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift @@ -19,7 +19,7 @@ open class AnotherFakeAPI { */ open class func testSpecialTags(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testSpecialTagsWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -41,8 +41,7 @@ open class AnotherFakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 660dd6b02f51..da291a94de40 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -18,7 +18,7 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerialize(body: OuterBoolean? = nil, completion: @escaping ((_ data: OuterBoolean?,_ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -37,8 +37,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -52,7 +51,7 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -75,8 +74,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -90,7 +88,7 @@ open class FakeAPI { */ open class func fakeOuterNumberSerialize(body: OuterNumber? = nil, completion: @escaping ((_ data: OuterNumber?,_ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -109,8 +107,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -124,7 +121,7 @@ open class FakeAPI { */ open class func fakeOuterStringSerialize(body: OuterString? = nil, completion: @escaping ((_ data: OuterString?,_ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -143,8 +140,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -159,7 +155,7 @@ open class FakeAPI { */ open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -181,8 +177,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -208,9 +203,13 @@ open class FakeAPI { - parameter callback: (form) None (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -262,9 +261,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -351,9 +349,13 @@ open class FakeAPI { - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -385,14 +387,13 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, "enum_query_integer": enumQueryInteger?.rawValue ]) - let nillableHeaders: [String: Any?] = [ "enum_header_string_array": enumHeaderStringArray, "enum_header_string": enumHeaderString?.rawValue @@ -410,9 +411,13 @@ open class FakeAPI { - parameter param: (body) request body - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: Any, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: Any, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -431,8 +436,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -446,9 +450,13 @@ open class FakeAPI { - parameter param2: (form) field2 - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -473,9 +481,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift index 228cee8ffbce..0e2a5670a8bb 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift @@ -19,7 +19,7 @@ open class FakeClassnameTags123API { */ open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -27,6 +27,7 @@ open class FakeClassnameTags123API { /** To test class name in snake case - PATCH /fake_classname_test + - To test class name in snake case - API Key: - type: apiKey api_key_query (QUERY) - name: api_key_query @@ -43,8 +44,7 @@ open class FakeClassnameTags123API { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index af0ed4d11c76..421bbe8e9d7d 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -17,9 +17,13 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + open class func addPet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -41,8 +45,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -56,9 +59,13 @@ open class PetAPI { - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -83,9 +90,8 @@ open class PetAPI { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey ] @@ -113,7 +119,7 @@ open class PetAPI { */ open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -218,12 +224,11 @@ open class PetAPI { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status ]) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -238,7 +243,7 @@ open class PetAPI { */ open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -343,12 +348,11 @@ open class PetAPI { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags ]) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -363,7 +367,7 @@ open class PetAPI { */ open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -439,9 +443,8 @@ open class PetAPI { path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -454,9 +457,13 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -478,8 +485,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -494,9 +500,13 @@ open class PetAPI { - parameter status: (form) Updated status of the pet (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -528,9 +538,8 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -547,7 +556,7 @@ open class PetAPI { */ open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -584,9 +593,8 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 2e050a3f04a7..571f4ef4e1e8 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -17,9 +17,13 @@ open class StoreAPI { - parameter orderId: (path) ID of the order that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -40,9 +44,8 @@ open class StoreAPI { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -56,7 +59,7 @@ open class StoreAPI { */ open class func getInventory(completion: @escaping ((_ data: [String:Int]?,_ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -78,9 +81,8 @@ open class StoreAPI { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -95,7 +97,7 @@ open class StoreAPI { */ open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -146,9 +148,8 @@ open class StoreAPI { path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -163,7 +164,7 @@ open class StoreAPI { */ open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -212,8 +213,7 @@ open class StoreAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 185fdac79772..028c5db34c34 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -17,9 +17,13 @@ open class UserAPI { - parameter body: (body) Created user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUser(body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -38,8 +42,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -52,9 +55,13 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -73,8 +80,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -87,9 +93,13 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -108,8 +118,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -122,9 +131,13 @@ open class UserAPI { - parameter username: (path) The name that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deleteUser(username: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -145,9 +158,8 @@ open class UserAPI { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -157,12 +169,12 @@ open class UserAPI { /** Get user by user name - - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter completion: completion handler to receive the data and the error objects */ open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -210,7 +222,7 @@ open class UserAPI { "username" : "username" }}] - - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - returns: RequestBuilder */ @@ -221,9 +233,8 @@ open class UserAPI { path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -239,7 +250,7 @@ open class UserAPI { */ open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -262,13 +273,12 @@ open class UserAPI { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username, "password": password ]) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -280,9 +290,13 @@ open class UserAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(completion: @escaping ((_ error: Error?) -> Void)) { + open class func logoutUser(completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -298,9 +312,8 @@ open class UserAPI { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -314,9 +327,13 @@ open class UserAPI { - parameter body: (body) Updated user object - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -339,8 +356,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 24351523736d..381fddcc81fb 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -268,7 +268,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift index 4cf4ac206af5..19ee06b1f487 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift @@ -24,4 +24,20 @@ open class JSONEncodingHelper { return params } + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { + var params: Parameters? = nil + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error) + return nil + } + } + + return params + } + } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift index 8388bfb035fc..6c1e6653b6f9 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift @@ -14,6 +14,10 @@ public struct AdditionalPropertiesClass: Codable { public var mapProperty: [String:String]? public var mapOfMapProperty: [String:[String:String]]? + public init(mapProperty: [String:String]?, mapOfMapProperty: [String:[String:String]]?) { + self.mapProperty = mapProperty + self.mapOfMapProperty = mapOfMapProperty + } public enum CodingKeys: String, CodingKey { case mapProperty = "map_property" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Animal.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Animal.swift index fa13d5e9b9f6..ba2da30fedde 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Animal.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Animal.swift @@ -14,6 +14,10 @@ public struct Animal: Codable { public var className: String public var color: String? + public init(className: String, color: String?) { + self.className = className + self.color = color + } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift index a4e416b79a85..3fd872dcd26f 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift @@ -15,6 +15,11 @@ public struct ApiResponse: Codable { public var type: String? public var message: String? + public init(code: Int?, type: String?, message: String?) { + self.code = code + self.type = type + self.message = message + } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift index 8aea70bfc69b..ac59328a279f 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift @@ -13,6 +13,9 @@ public struct ArrayOfArrayOfNumberOnly: Codable { public var arrayArrayNumber: [[Double]]? + public init(arrayArrayNumber: [[Double]]?) { + self.arrayArrayNumber = arrayArrayNumber + } public enum CodingKeys: String, CodingKey { case arrayArrayNumber = "ArrayArrayNumber" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift index c670c41c217e..1132638458fc 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift @@ -13,6 +13,9 @@ public struct ArrayOfNumberOnly: Codable { public var arrayNumber: [Double]? + public init(arrayNumber: [Double]?) { + self.arrayNumber = arrayNumber + } public enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift index 6257fb4cc9bb..14335a750539 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift @@ -15,6 +15,11 @@ public struct ArrayTest: Codable { public var arrayArrayOfInteger: [[Int64]]? public var arrayArrayOfModel: [[ReadOnlyFirst]]? + public init(arrayOfString: [String]?, arrayArrayOfInteger: [[Int64]]?, arrayArrayOfModel: [[ReadOnlyFirst]]?) { + self.arrayOfString = arrayOfString + self.arrayArrayOfInteger = arrayArrayOfInteger + self.arrayArrayOfModel = arrayArrayOfModel + } public enum CodingKeys: String, CodingKey { case arrayOfString = "array_of_string" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift index 952c337fa740..71ba400a9d7b 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -19,6 +19,14 @@ public struct Capitalization: Codable { /** Name of the pet */ public var ATT_NAME: String? + public init(smallCamel: String?, capitalCamel: String?, smallSnake: String?, capitalSnake: String?, sCAETHFlowPoints: String?, ATT_NAME: String?) { + self.smallCamel = smallCamel + self.capitalCamel = capitalCamel + self.smallSnake = smallSnake + self.capitalSnake = capitalSnake + self.sCAETHFlowPoints = sCAETHFlowPoints + self.ATT_NAME = ATT_NAME + } public enum CodingKeys: String, CodingKey { case smallCamel diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Cat.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Cat.swift index e9e061b5e364..7687f52d477a 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Cat.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Cat.swift @@ -15,6 +15,11 @@ public struct Cat: Codable { public var color: String? public var declawed: Bool? + public init(className: String, color: String?, declawed: Bool?) { + self.className = className + self.color = color + self.declawed = declawed + } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Category.swift index 2975a53a5079..fa0786832c63 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Category.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -14,6 +14,10 @@ public struct Category: Codable { public var _id: Int64? public var name: String? + public init(_id: Int64?, name: String?) { + self._id = _id + self.name = name + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift index 90da5c2cf4dc..3a38128215a2 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift @@ -14,6 +14,9 @@ public struct ClassModel: Codable { public var _class: String? + public init(_class: String?) { + self._class = _class + } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Client.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Client.swift index f4333883e631..0c4fc0d559a9 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Client.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Client.swift @@ -13,6 +13,9 @@ public struct Client: Codable { public var client: String? + public init(client: String?) { + self.client = client + } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Dog.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Dog.swift index b86c61c0ee34..9ba84f7f8cc5 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Dog.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Dog.swift @@ -15,6 +15,11 @@ public struct Dog: Codable { public var color: String? public var breed: String? + public init(className: String, color: String?, breed: String?) { + self.className = className + self.color = color + self.breed = breed + } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift index 145acd9dd347..084a9ab83836 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift @@ -22,6 +22,10 @@ public struct EnumArrays: Codable { public var justSymbol: JustSymbol? public var arrayEnum: [ArrayEnum]? + public init(justSymbol: JustSymbol?, arrayEnum: [ArrayEnum]?) { + self.justSymbol = justSymbol + self.arrayEnum = arrayEnum + } public enum CodingKeys: String, CodingKey { case justSymbol = "just_symbol" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index 74b693c7bb61..6374df494a32 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -16,6 +16,11 @@ public struct EnumTest: Codable { case lower = "lower" case empty = "" } + public enum EnumStringRequired: String, Codable { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } public enum EnumInteger: Int, Codable { case _1 = 1 case number1 = -1 @@ -25,13 +30,22 @@ public struct EnumTest: Codable { case number12 = -1.2 } public var enumString: EnumString? + public var enumStringRequired: EnumStringRequired public var enumInteger: EnumInteger? public var enumNumber: EnumNumber? public var outerEnum: OuterEnum? + public init(enumString: EnumString?, enumStringRequired: EnumStringRequired, enumInteger: EnumInteger?, enumNumber: EnumNumber?, outerEnum: OuterEnum?) { + self.enumString = enumString + self.enumStringRequired = enumStringRequired + self.enumInteger = enumInteger + self.enumNumber = enumNumber + self.outerEnum = outerEnum + } public enum CodingKeys: String, CodingKey { case enumString = "enum_string" + case enumStringRequired = "enum_string_required" case enumInteger = "enum_integer" case enumNumber = "enum_number" case outerEnum diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift index 0ce1edc16b07..1fc4bd362fd1 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift @@ -25,6 +25,21 @@ public struct FormatTest: Codable { public var uuid: UUID? public var password: String + public init(integer: Int?, int32: Int?, int64: Int64?, number: Double, float: Float?, double: Double?, string: String?, byte: Data, binary: Data?, date: Date, dateTime: Date?, uuid: UUID?, password: String) { + self.integer = integer + self.int32 = int32 + self.int64 = int64 + self.number = number + self.float = float + self.double = double + self.string = string + self.byte = byte + self.binary = binary + self.date = date + self.dateTime = dateTime + self.uuid = uuid + self.password = password + } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift index 23f5e679faf3..3626846919f5 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift @@ -14,6 +14,10 @@ public struct HasOnlyReadOnly: Codable { public var bar: String? public var foo: String? + public init(bar: String?, foo: String?) { + self.bar = bar + self.foo = foo + } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/List.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/List.swift index 382702867a89..fe11bfce8402 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/List.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/List.swift @@ -13,6 +13,9 @@ public struct List: Codable { public var _123List: String? + public init(_123List: String?) { + self._123List = _123List + } public enum CodingKeys: String, CodingKey { case _123List = "123-list" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MapTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MapTest.swift index e8f11504de5d..ded3f7b1dde1 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MapTest.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MapTest.swift @@ -18,6 +18,10 @@ public struct MapTest: Codable { public var mapMapOfString: [String:[String:String]]? public var mapOfEnumString: [String:String]? + public init(mapMapOfString: [String:[String:String]]?, mapOfEnumString: [String:String]?) { + self.mapMapOfString = mapMapOfString + self.mapOfEnumString = mapOfEnumString + } public enum CodingKeys: String, CodingKey { case mapMapOfString = "map_map_of_string" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 554c81317eb4..962b7fe65bc5 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -15,6 +15,11 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { public var dateTime: Date? public var map: [String:Animal]? + public init(uuid: UUID?, dateTime: Date?, map: [String:Animal]?) { + self.uuid = uuid + self.dateTime = dateTime + self.map = map + } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift index 573cb42acfd4..f539cd888ab5 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift @@ -15,6 +15,10 @@ public struct Model200Response: Codable { public var name: Int? public var _class: String? + public init(name: Int?, _class: String?) { + self.name = name + self._class = _class + } public enum CodingKeys: String, CodingKey { case name diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Name.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Name.swift index b4686c2c8a4c..ddd2b9098519 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Name.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Name.swift @@ -17,6 +17,12 @@ public struct Name: Codable { public var property: String? public var _123Number: Int? + public init(name: Int, snakeCase: Int?, property: String?, _123Number: Int?) { + self.name = name + self.snakeCase = snakeCase + self.property = property + self._123Number = _123Number + } public enum CodingKeys: String, CodingKey { case name diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift index 78bb76f9bfd6..06db22e9c3ab 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift @@ -13,6 +13,9 @@ public struct NumberOnly: Codable { public var justNumber: Double? + public init(justNumber: Double?) { + self.justNumber = justNumber + } public enum CodingKeys: String, CodingKey { case justNumber = "JustNumber" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Order.swift index 26de6d8313dc..b6c0cc0cb5a2 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -24,6 +24,14 @@ public struct Order: Codable { public var status: Status? public var complete: Bool? + public init(_id: Int64?, petId: Int64?, quantity: Int?, shipDate: Date?, status: Status?, complete: Bool?) { + self._id = _id + self.petId = petId + self.quantity = quantity + self.shipDate = shipDate + self.status = status + self.complete = complete + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift index 0c77ca23f503..bd1984e870db 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift @@ -15,6 +15,11 @@ public struct OuterComposite: Codable { public var myString: OuterString? public var myBoolean: OuterBoolean? + public init(myNumber: OuterNumber?, myString: OuterString?, myBoolean: OuterBoolean?) { + self.myNumber = myNumber + self.myString = myString + self.myBoolean = myBoolean + } public enum CodingKeys: String, CodingKey { case myNumber = "my_number" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift index dcb32870f70a..73985167c966 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -24,6 +24,14 @@ public struct Pet: Codable { /** pet status in the store */ public var status: Status? + public init(_id: Int64?, category: Category?, name: String, photoUrls: [String], tags: [Tag]?, status: Status?) { + self._id = _id + self.category = category + self.name = name + self.photoUrls = photoUrls + self.tags = tags + self.status = status + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift index 7cec5cb2f927..6e984760cd6c 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift @@ -14,6 +14,10 @@ public struct ReadOnlyFirst: Codable { public var bar: String? public var baz: String? + public init(bar: String?, baz: String?) { + self.bar = bar + self.baz = baz + } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Return.swift index 86c3f0d8097f..9502f08130c1 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Return.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Return.swift @@ -14,6 +14,9 @@ public struct Return: Codable { public var _return: Int? + public init(_return: Int?) { + self._return = _return + } public enum CodingKeys: String, CodingKey { case _return = "return" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift index f0c0aec53944..f94741a854a3 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift @@ -13,6 +13,9 @@ public struct SpecialModelName: Codable { public var specialPropertyName: Int64? + public init(specialPropertyName: Int64?) { + self.specialPropertyName = specialPropertyName + } public enum CodingKeys: String, CodingKey { case specialPropertyName = "$special[property.name]" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift index 86c19a254d14..7dd17159a739 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -14,6 +14,10 @@ public struct Tag: Codable { public var _id: Int64? public var name: String? + public init(_id: Int64?, name: String?) { + self._id = _id + self.name = name + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/User.swift index ab73f62883e5..09b68da4f8f4 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/User.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -21,6 +21,16 @@ public struct User: Codable { /** User Status */ public var userStatus: Int? + public init(_id: Int64?, username: String?, firstName: String?, lastName: String?, email: String?, password: String?, phone: String?, userStatus: Int?) { + self._id = _id + self.username = username + self.firstName = firstName + self.lastName = lastName + self.email = email + self.password = password + self.phone = phone + self.userStatus = userStatus + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift4/default/SwaggerClientTests/Podfile.lock index dbc19e59b6a5..2136cf45f3ba 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Podfile.lock +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Podfile.lock @@ -1,7 +1,7 @@ PODS: - Alamofire (4.5.0) - PetstoreClient (0.0.1): - - Alamofire (~> 4.5) + - Alamofire (~> 4.5.0) DEPENDENCIES: - PetstoreClient (from `../`) @@ -12,8 +12,8 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: Alamofire: f28cdffd29de33a7bfa022cbd63ae95a27fae140 - PetstoreClient: 224b8a1c6244bcba3eef8fc2d64ff398a014f7c8 + PetstoreClient: fef7934ac90bd28c2b81cc5234615112f9ace5f5 PODFILE CHECKSUM: 417049e9ed0e4680602b34d838294778389bd418 -COCOAPODS: 1.3.1 +COCOAPODS: 1.4.0 diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json index 613c1411ce88..ef3562909be4 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -2,7 +2,8 @@ "name": "PetstoreClient", "platforms": { "ios": "9.0", - "osx": "10.11" + "osx": "10.11", + "tvos": "9.0" }, "version": "0.0.1", "source": { @@ -16,7 +17,7 @@ "source_files": "PetstoreClient/Classes/**/*.swift", "dependencies": { "Alamofire": [ - "~> 4.5" + "~> 4.5.0" ] } } diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Manifest.lock index dbc19e59b6a5..2136cf45f3ba 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Manifest.lock +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Manifest.lock @@ -1,7 +1,7 @@ PODS: - Alamofire (4.5.0) - PetstoreClient (0.0.1): - - Alamofire (~> 4.5) + - Alamofire (~> 4.5.0) DEPENDENCIES: - PetstoreClient (from `../`) @@ -12,8 +12,8 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: Alamofire: f28cdffd29de33a7bfa022cbd63ae95a27fae140 - PetstoreClient: 224b8a1c6244bcba3eef8fc2d64ff398a014f7c8 + PetstoreClient: fef7934ac90bd28c2b81cc5234615112f9ace5f5 PODFILE CHECKSUM: 417049e9ed0e4680602b34d838294778389bd418 -COCOAPODS: 1.3.1 +COCOAPODS: 1.4.0 diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj index 9752f3ad2c9a..c54f9d521640 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -7,87 +7,88 @@ objects = { /* Begin PBXBuildFile section */ - 0F662FA5B2EB748EA516B8C83742DE29 /* EnumArrays.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88EC57640E276EA2387256530FB1F868 /* EnumArrays.swift */; }; + 04B6872F088373A5D9622389D44ABFA7 /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C78CDA7E4BB301D917FE7CFBD2457EF /* APIHelper.swift */; }; + 07EEC7822D7CB95755A6BB464B2BF1D1 /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 697B1649F70C9355E6ED995300DBBA28 /* APIs.swift */; }; + 0D2084CADDB0230A4CAF2C0605F828DF /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CAF4F2E2C16A07E038AAA59349BBCD9 /* AlamofireImplementations.swift */; }; 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87882A1F5A92C8138D54545E51D51E6F /* Timeline.swift */; }; - 127354085F10006D6B57C16D3AE2E043 /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 897799EBBCCE802354256F9E7984C2CF /* StoreAPI.swift */; }; - 1982792C8B5D5B4999228D16CDBE3E28 /* EnumTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3941FB77CA24840ADF5671D16FE460C /* EnumTest.swift */; }; - 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = B44A27EFBB0DA84D738057B77F3413B1 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 24F9EAC555D87891496C9873A3A353BC /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3ED6F43B3A7602CD88ED67B9873B2036 /* Models.swift */; }; - 281150C5E93967FEA2D3921AEC92BA3D /* SpecialModelName.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7E7932024A79370E61700F5FD439D37 /* SpecialModelName.swift */; }; - 2B1BE5C3FED4683F31A1DA3E4D4FE6C6 /* AdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3153AF6539569349FDEA90444438B8A /* AdditionalPropertiesClass.swift */; }; - 2B22A023463A6CF04BB1BFF869D30AC6 /* ClassModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = C925A1EF89E6AF23AE6EA4BA515A6E11 /* ClassModel.swift */; }; - 2D208564DFB2C2849316BD87AA3F53AC /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9930F8E68307FDF3470DAFB398895B2 /* APIHelper.swift */; }; - 31F8B86E3672D0B828B6352C875649C4 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1271FFC6225DD34662309214506624E3 /* HasOnlyReadOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFD9B6C73F406E259D12AAD66EB86E3A /* HasOnlyReadOnly.swift */; }; + 12E1368A8649F7ABCA22122BB086A9A4 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32EFBC701E63AE331BC0BF170B2C1E2B /* User.swift */; }; + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 03DECE84DC850B04690604AB7C521277 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 229E82D3A37D202BFF958E8278C2E5D0 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EF8BA4CB172F8F6925C18B674169419 /* Pet.swift */; }; + 2361B453C0E27F769982D2E157DFD27B /* EnumClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF4FEED941249256FD7E23C19D4567AC /* EnumClass.swift */; }; + 27AFC4AEBB1B56DD719675A2118CCB8D /* JSONEncodingHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = F46B1129B323D17632F7089F71632F60 /* JSONEncodingHelper.swift */; }; + 28832E8D2FFAF4A8A372893866A96CD3 /* Capitalization.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD18CDAD22507BB2C69589FD60138F66 /* Capitalization.swift */; }; + 3185145561047965FB52DD80ED69B7C8 /* FakeClassnameTags123API.swift in Sources */ = {isa = PBXBuildFile; fileRef = A145777600D2D0E2B9427EEE317DF443 /* FakeClassnameTags123API.swift */; }; + 31B8C21D76FE98AE41B88A44169ECE84 /* NumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3036A4C6739CD7F9D802133405FB095 /* NumberOnly.swift */; }; + 31F8B86E3672D0B828B6352C875649C4 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = CF1ECC5499BE9BF36F0AE0CE47ABB673 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3322B46E9D9AFB13466804547F6404A4 /* OuterEnum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E5EF70E686134181F06537A75BA0FD2 /* OuterEnum.swift */; }; 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A01C037B4034EDA3D7955BC5E4E9D9D6 /* TaskDelegate.swift */; }; - 363930DE8DE4B17D8EF901F5C249A9AC /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24D3039E712D1279434152E805AEDA65 /* Order.swift */; }; - 39C0CB11CA9812CD5BB73A893D27BEE9 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 158D0513D0844E7FE6AEFAEE70E88618 /* UserAPI.swift */; }; - 3B0E9022805FED1731E3C6474C700253 /* CodableHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7EA034E64EC60C1FCC5609CA9962CD51 /* CodableHelper.swift */; }; - 3E11073F08C80332AEFC3A10FC489313 /* AnimalFarm.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3862A83F9BE857B1E903ABBBDE37EF7 /* AnimalFarm.swift */; }; + 36505FE5A99837291C843D5627689950 /* ReadOnlyFirst.swift in Sources */ = {isa = PBXBuildFile; fileRef = 896B006368E7DC47A51391033A97C2EE /* ReadOnlyFirst.swift */; }; + 36E58F38207F15EBD91ADCEF62C7C85E /* List.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEE2B177461F2E7FC327D113FEC55D4 /* List.swift */; }; + 3EDE1BCF1CAE7C657EA278797CA70181 /* Fake_classname_tags123API.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49BB1DA804C4AA7D9FEF0DC43604CCCE /* Fake_classname_tags123API.swift */; }; 3F3B788CC8A53F01CE6A1B33D4052D80 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0D0533E4EC2277AAAC8888328EC5A64B /* Foundation.framework */; }; - 424F25F3C040D2362DD353C82A86740B /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 472DF233EF1CA028A52DB57F87A5687F /* FakeClassnameTags123API.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AE3690E05FA4B6B3A8600FCA1631D8C /* FakeClassnameTags123API.swift */; }; - 4814A739814A3809C4D9C61F96012C62 /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7417953898146193F86A165CD5F3AF4A /* Category.swift */; }; - 4CBD58C64013924FB5A74A106D838285 /* FormatTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9776B33259DFB803A3E6D9573FA3DE3E /* FormatTest.swift */; }; - 4DF5B60FEFEAC2BA370EE79D2567B3E9 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4B3F69D54C19FC502362EEE3544ECA0 /* User.swift */; }; + 424F25F3C040D2362DD353C82A86740B /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 32432BEBC9EDBC5E269C9AA0E570F464 /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 450A1F9D9F0C0316DC5571EAD3C7FFB6 /* FakeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 456356DFF7271B4F562B7F04E03E3CA8 /* FakeAPI.swift */; }; + 46899B04EA5D619054AACDD9C5F2F7B5 /* AdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 374D32747BDC0BDD7ACFF23F5BF910C3 /* AdditionalPropertiesClass.swift */; }; + 52661A921B6F46145CE16E108CA3C1CD /* Cat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36EB25B2EACD40B282A658DA456B0FED /* Cat.swift */; }; 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E230A0448B394DE26E688DAC8E6201E /* Request.swift */; }; - 55F9C83CA76F9B2DA873122BEC278855 /* Name.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C0EF68B5117187E979D1DE4ECDB938E /* Name.swift */; }; - 5E38839B97A3FB54831CB0CE3B177E06 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 411BB07BE03DCC7000891F6A5E62BBC6 /* Configuration.swift */; }; - 5EC075C471A4F4D9A43857B8629D95EE /* ReadOnlyFirst.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A0977DBA9BAE46013DFD65E4400A0CB /* ReadOnlyFirst.swift */; }; + 55013BF8F5D5A6B238473A65819BA91E /* AnotherfakeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51830C53E0E76A54309CE2137E716625 /* AnotherfakeAPI.swift */; }; + 5C76B11759683109F447BA67F28F83DC /* EnumArrays.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30C1E56142D8B120BDDE2AF5CA160E22 /* EnumArrays.swift */; }; + 5F18574D9A8C0B088105A657C4EBFE8A /* MapTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38F502D93EB2D1D9C2A1283F96BFF4D2 /* MapTest.swift */; }; 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FCBF1EED873F61C6D46CE37FA5C39D3 /* DispatchQueue+Alamofire.swift */; }; 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32B030D27CAC730C5EB0F22390645310 /* ServerTrustPolicy.swift */; }; - 707F832EEA6E7DD274201962E4D85B5B /* OuterComposite.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AE839994FB9B18B77FC95BCC9594683 /* OuterComposite.swift */; }; + 6FD39FEAAFE27DBC3EC0F11B20D97734 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AEE7AA4D6A19965503F1889B1F44B1D /* Models.swift */; }; 73B9C996AED49ED7CF8EC2A6F1738059 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0D0533E4EC2277AAAC8888328EC5A64B /* Foundation.framework */; }; - 73BF6D173C637DEE9571E96E19EADABD /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0D0533E4EC2277AAAC8888328EC5A64B /* Foundation.framework */; }; - 74E60841671B65510C2E9DBD34EDD96B /* ArrayOfArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B900B675208453FB7767B0D97D50932 /* ArrayOfArrayOfNumberOnly.swift */; }; - 7A854DC997BF3D7E3449FF58278EC967 /* NumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A332587F10679E262455F979B3D1055 /* NumberOnly.swift */; }; + 749396546BA912EA0DD0A0A38FDEDAA4 /* Name.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E3B882B966B7AF813A56A7DA9DA1F1C /* Name.swift */; }; 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 195D73DD9EF275A3C56569E2B1CA8026 /* SessionDelegate.swift */; }; 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D60BC9955B4F7FFA62D7440CB385C11 /* Result.swift */; }; - 7D99F1CDFA55B21CBDB1603DA46C0599 /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 3B26D25AFB2018A320BA1C7EDE3F560C /* PetstoreClient-dummy.m */; }; - 7EE07906770CB8D69F00429072D7DC02 /* FakeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C6145F09A87143B7FC501BE989C8BBD /* FakeAPI.swift */; }; - 8158ED5AEE2D6FE60EBA456F691D823C /* JSONEncodableEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 466D426E7AA31C27ABC601DD606EF126 /* JSONEncodableEncoding.swift */; }; - 82F7587E619353285C601A5677961853 /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 854F6A83AC5201A267F39995BF249D32 /* AlamofireImplementations.swift */; }; - 857A7B68378E7164FD99F549C092436E /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02E62B78D97471D708B23605FCAA9EA1 /* Tag.swift */; }; - 897985FA042CD12B825C3032898FAB26 /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; - 8A4C36FD6B751F6F87BFC6C4E01DD793 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 475EFFB863F38801DE73965C1438E2FF /* PetAPI.swift */; }; - 9067B627206EA4FFE8E94388031FBB70 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = C0C60220F2C965335A15C6C5688ACE4F /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 90D416A6F921DADEF05F65AFF7E1E5B0 /* Cat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4530F24A4BDA094563779F1D4313B9E1 /* Cat.swift */; }; - 9145FC4EDCAF00080761172112D6B4E1 /* EnumClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30E08D3E06CED1E4F2876EFA44A239ED /* EnumClass.swift */; }; - 96179D2776662CFF1D8CD2BA7599E165 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */; }; - 973AF350C705E18926C330359F0DAC29 /* Model200Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3617A5AF85A2814F852C73FD5D575262 /* Model200Response.swift */; }; - 9B73E49DCB45F1F471FA4DE8264BA512 /* MapTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF26681AB7FB981F237CD8EA4F059708 /* MapTest.swift */; }; + 802D6A4D73A1A03F0F30D814126EC859 /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98A8E010F6244706560DDC29B122EBAF /* StoreAPI.swift */; }; + 8106FA532C222AE698AF0D473D8C9160 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC6A834DBFB72DAA5CF0C32268CDF605 /* Configuration.swift */; }; + 84FCC3BCB6219E32B67168629345B43F /* ClassModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 828ED4B097AAB98D5568D37B8AECAFD0 /* ClassModel.swift */; }; + 862F16E17E79FAA53D395CE275546D28 /* Return.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB0F6DF945AB4286D73C45A2139ED7B3 /* Return.swift */; }; + 897985FA042CD12B825C3032898FAB26 /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 721957E37E3EE5DB5F8DBF20A032B42A /* Pods-SwaggerClientTests-dummy.m */; }; + 9BD5D264F2B563611262E196A5961066 /* OuterString.swift in Sources */ = {isa = PBXBuildFile; fileRef = D752057107F19596D3B8EA574206B2F2 /* OuterString.swift */; }; + 9D4858FD9A6340A4609BEBDF00C382F9 /* ArrayOfArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = A08C7F48AC7ABF4E88804808C4EB68F1 /* ArrayOfArrayOfNumberOnly.swift */; }; 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AF006B0AD5765D1BFA8253C2DCBB126 /* AFError.swift */; }; - 9F4FF785FA604AD3A70C4B87FA0ED450 /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3581DEB2B2BDC3D8A0BF7C43BD317506 /* APIs.swift */; }; - A0F161A5D21EFF05B0208B7C1B6C3C67 /* OuterString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EB640315A574EA2C8E4584499B31A44 /* OuterString.swift */; }; + A0AD98559666C4BA8E74CA46211B44F2 /* OuterNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC665263E59F937C09C52DBC4851F44F /* OuterNumber.swift */; }; A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5A8AA5F9EDED0A0BDDE7E830BF4AEE0 /* NetworkReachabilityManager.swift */; }; - A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 22C1C119BCE81C53F76CAC2BE27C38E0 /* Alamofire-dummy.m */; }; - AAEFA9B66A1EE281AA8D76AC0DCA3C97 /* JSONEncodingHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB3DDF6C3277994828CD09F3155BB74E /* JSONEncodingHelper.swift */; }; + A57FEBD11E8DC63EF939F8183779BECA /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 712969C66751DDCC0D484F06819ADFAF /* PetAPI.swift */; }; + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D1F50F37DFB6DC0B7B9D8C373E5A3EAE /* Alamofire-dummy.m */; }; AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46CDAC6C1187C5467E576980E1062C8B /* SessionManager.swift */; }; - B384569B4208ADC0A68233491ED19609 /* Animal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8689097AED0350F905AFA5B0962FA969 /* Animal.swift */; }; - B4D9507C3602C7D37EB6F7B88269CD52 /* ArrayTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30B827D77F92D24E6D24561F491F2A50 /* ArrayTest.swift */; }; - B65AABE5C7EB03365333C4783B36CCDC /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = F05D3E8C18F8C0EF732558438FAA421A /* Extensions.swift */; }; + B116548930626181CC1301D0ADE31720 /* Client.swift in Sources */ = {isa = PBXBuildFile; fileRef = C26CC9E49237A04F52DC71125A1756AB /* Client.swift */; }; + B13CE8FE8573C0FB07C97D0C34DD9CF4 /* OuterBoolean.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD15E529B026F88FF8EAE32BD84D468D /* OuterBoolean.swift */; }; B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 155538D91ACEEEDF82069ACF6C1A02E7 /* MultipartFormData.swift */; }; - BA15A21EB63AC8A5B7B859AC8D6E7B23 /* List.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B87E0BA794A79025212F37D32449C63 /* List.swift */; }; BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = B029DBC43E49A740F12B5E4D2E6DD452 /* Validation.swift */; }; + BCBC0EA84005299246354BB70B11301B /* Dog.swift in Sources */ = {isa = PBXBuildFile; fileRef = E28B79A691A2192E2A8595ACB60CC54C /* Dog.swift */; }; + BCFCE38A7F2EBB043C581F2A24947FEA /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84B5DCFB56EC99326DEBD055A032458E /* Category.swift */; }; + BD15F885C0DB08C2BA875B3A36DFD778 /* Model200Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF3A2EA92DAC72BC0CED7B12F16198BD /* Model200Response.swift */; }; BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6639346628280A0D0FAD35196BF56108 /* ParameterEncoding.swift */; }; - C888F5D0484D08C3F110B48DF18DDFD6 /* Return.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87DCB85380B2EC22CFE743BEDE7E4114 /* Return.swift */; }; - CA6B474618AA720ABFB571F69B227AF7 /* OuterEnum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13C6EEF1D81A0C523AE569F1732AC8DC /* OuterEnum.swift */; }; + BF7DF71571E51EBF9CF76436ADA68ACA /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 987E88064EF735B91468D5018C18E261 /* Extensions.swift */; }; + C40D07E49370F6A2B17F2AA7D8B5B8A5 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 55CCB86279C9704891B8B855CA6380F6 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C7DAA30310B69C6742610B5EBC23B328 /* OuterComposite.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9F529192DED719D7A55A3E804866F26 /* OuterComposite.swift */; }; CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04F47F5C9CDB035C5AFADEBA5BF44F1C /* Response.swift */; }; - D54B91C71FC0918800319969 /* AnotherfakeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = D54B91C61FC0918800319969 /* AnotherfakeAPI.swift */; }; - D5F1BBD60108412FD5C8B320D20B2993 /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; - DE8F9190013C0FECA7C3413F214B2BAB /* ApiResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3102957D0FBF5FFA80969BB2A15F8FF /* ApiResponse.swift */; }; - E05C5957E89CE7129CC4880299444A81 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1FF93AC280A80800873A20A8F72AD29 /* Pet.swift */; }; - E0B2924D681BAA663ADE94DC43706E3D /* Capitalization.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0A482A15F21B4BC206B31E7A0FAB79F /* Capitalization.swift */; }; - E0C687FEA77962F5E1CE2D4347246984 /* ArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45CB52E75AED2F044F187FD71FDFC880 /* ArrayOfNumberOnly.swift */; }; - E6A0A5C14D3633FFE1551CFDE39FA4C3 /* Dog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28F73294B64CD8821EC2467CB7F1F073 /* Dog.swift */; }; + CB9A39C25CA7ED02B7E02B5AA1354911 /* Animal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 171602313BBD5AE0D5F50FFB70A96CED /* Animal.swift */; }; + CC1ABC7D57D24128BCE892C928EB155D /* JSONEncodableEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5EB60B9D147E1DCD36D55283254A515 /* JSONEncodableEncoding.swift */; }; + D0FD45C03A13220C2DEC62BE2330FC92 /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EB94F5F2FE938ECEA46481E25FFA28F /* Order.swift */; }; + D0FF9ABBD288F188E54D3CAB5208202B /* ArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = B99164AE8FDE28FAD698B280AC716F77 /* ArrayOfNumberOnly.swift */; }; + D5F1BBD60108412FD5C8B320D20B2993 /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FCC3BC0A0823C3FF68C4E1EF67B2FD /* Pods-SwaggerClient-dummy.m */; }; + DA774D60BA836CC50DCEF3F0402A0D25 /* ArrayTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 584CE59DFDF2D30A308478C17A426ADA /* ArrayTest.swift */; }; + DD24D51FC8B3C4AE95827418EC5D5EF3 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */; }; + E0559707E3DAE5B759A2570EE64AEF37 /* CodableHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06D5E6CDDEE294F817C22C521B562508 /* CodableHelper.swift */; }; + E0FC0F7FCAAFB628D17EB6277E6384D0 /* ApiResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 670103307A767288F991B17974F3E258 /* ApiResponse.swift */; }; + E24BD2C6E31CACD58555DB8044F7EFE4 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 364DFA113368D39E8F9FF776C3C78B11 /* UserAPI.swift */; }; + E661B7CF775527BE72A5B2D4EB5F73E8 /* AnimalFarm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F80C8976AE5FBE0927AD59150439B97 /* AnimalFarm.swift */; }; E723EED99F633C8620915572700A2D2E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0D0533E4EC2277AAAC8888328EC5A64B /* Foundation.framework */; }; - EA063534695F7232C7E7FF9C5A61483A /* OuterNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BA93068A5B18A779CC9B0FC3F685400 /* OuterNumber.swift */; }; - EDFB99BED377CAB8D24E0256E1208BD1 /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FB1FE2028948C532392F549A4356FBC /* MixedPropertiesAndAdditionalPropertiesClass.swift */; }; + E7ADAAB656F28A756189B278B28D0099 /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 791E26F1F38D683DDDDF5B5A4B3D6607 /* MixedPropertiesAndAdditionalPropertiesClass.swift */; }; EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66A46F517F0AF7E85A16D723F6406896 /* Notifications.swift */; }; - F1ACDB1E74FDDF4609EA027BB6D5C9D8 /* OuterBoolean.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21A143975CF52EBFEF79A307CC7CB00E /* OuterBoolean.swift */; }; + F3728DB3E73B9E46DCCD1FBB17888A31 /* FormatTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4F28D074D15DD5B49DC39B3706C7C87 /* FormatTest.swift */; }; + F4749A9FA396C6C94CF4F4D16897A60C /* SpecialModelName.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F72B7A542B1D04D38B262F407D0F92F /* SpecialModelName.swift */; }; F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2F9510473F6FFD7AA66524DB16C2263 /* ResponseSerialization.swift */; }; - F81E110F1F9AAD6C448DCF5DF99C2F41 /* Client.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B8F990A8905B95231C6D1955750D23C /* Client.swift */; }; + F7D10D5D6C92E40C736C597872B7F9BD /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = B988BD8876FEE563F8D7A6E2534BA48B /* Tag.swift */; }; + F88A1839757ADAA76A5A40A3149E5B45 /* EnumTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 289EF031EA3B2CA318F7EACE05641165 /* EnumTest.swift */; }; F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFCB8C44DE758E906C0BCDA455937B85 /* Alamofire.swift */; }; - F9884BC36100EA0FC9AAABAC5D4A0371 /* HasOnlyReadOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5DF7C9C577375BE47CAE380DE3EBE19 /* HasOnlyReadOnly.swift */; }; + F8CBD4B50C45BCC72F66D919E4E37F6A /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 0467D138A3101545CABA11DDD745B87B /* PetstoreClient-dummy.m */; }; + F8D1A2541DD038CBD649F825DBD1DF63 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0D0533E4EC2277AAAC8888328EC5A64B /* Foundation.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -95,17 +96,17 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = F273DBB2E19E2286018971F2B25DEB52; + remoteGlobalIDString = 691AAEA1153824FE132C368C2B9D4ECF; remoteInfo = PetstoreClient; }; - 53846F4D999F8096A92BE0AB60034710 /* PBXContainerItemProxy */ = { + F9E1549CFEDAD61BECA92DB5B12B4019 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; remoteInfo = Alamofire; }; - F9E1549CFEDAD61BECA92DB5B12B4019 /* PBXContainerItemProxy */ = { + FAEF364FCCB241333BC2531394A7BC5A /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; @@ -115,130 +116,132 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; - 02E62B78D97471D708B23605FCAA9EA1 /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; - 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; + 03DECE84DC850B04690604AB7C521277 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 0467D138A3101545CABA11DDD745B87B /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; 04F47F5C9CDB035C5AFADEBA5BF44F1C /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; - 0BA93068A5B18A779CC9B0FC3F685400 /* OuterNumber.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterNumber.swift; sourceTree = ""; }; + 06D5E6CDDEE294F817C22C521B562508 /* CodableHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CodableHelper.swift; path = PetstoreClient/Classes/Swaggers/CodableHelper.swift; sourceTree = ""; }; + 08BDFE9C9E9365771FF2D47928E3E79A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; + 0AD61F8554C909A3AFA66AD9ECCB5F23 /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; 0D0533E4EC2277AAAC8888328EC5A64B /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; 0FCBF1EED873F61C6D46CE37FA5C39D3 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; - 13A0A663B36A229C69D5274A83E93F88 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 13C6EEF1D81A0C523AE569F1732AC8DC /* OuterEnum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterEnum.swift; sourceTree = ""; }; + 117EFB31D9AD9673BAF51B48596F19E2 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 155538D91ACEEEDF82069ACF6C1A02E7 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; - 158D0513D0844E7FE6AEFAEE70E88618 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; + 171602313BBD5AE0D5F50FFB70A96CED /* Animal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Animal.swift; sourceTree = ""; }; 195D73DD9EF275A3C56569E2B1CA8026 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; - 1B900B675208453FB7767B0D97D50932 /* ArrayOfArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfArrayOfNumberOnly.swift; sourceTree = ""; }; + 19CFD6BC7040A5BC22831D4B5EB7F793 /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = PetstoreClient.modulemap; sourceTree = ""; }; + 1ACCB3378E1513AEAADC85C4036257E4 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; 1E230A0448B394DE26E688DAC8E6201E /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; - 21A143975CF52EBFEF79A307CC7CB00E /* OuterBoolean.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterBoolean.swift; sourceTree = ""; }; - 22C1C119BCE81C53F76CAC2BE27C38E0 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; - 24D3039E712D1279434152E805AEDA65 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; - 28F73294B64CD8821EC2467CB7F1F073 /* Dog.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Dog.swift; sourceTree = ""; }; - 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; - 2A332587F10679E262455F979B3D1055 /* NumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NumberOnly.swift; sourceTree = ""; }; - 2ACC287E45C0FCE8717A34B8ECA88A30 /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = ""; }; - 2AE3690E05FA4B6B3A8600FCA1631D8C /* FakeClassnameTags123API.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeClassnameTags123API.swift; sourceTree = ""; }; - 2C0EF68B5117187E979D1DE4ECDB938E /* Name.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Name.swift; sourceTree = ""; }; - 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; - 30B827D77F92D24E6D24561F491F2A50 /* ArrayTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayTest.swift; sourceTree = ""; }; - 30E08D3E06CED1E4F2876EFA44A239ED /* EnumClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumClass.swift; sourceTree = ""; }; + 1E9A49B1D85B7A38F2CAD05F245B27C3 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 210971763CB2FC0DC4E378271A37BE32 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + 289EF031EA3B2CA318F7EACE05641165 /* EnumTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumTest.swift; sourceTree = ""; }; + 2AEE7AA4D6A19965503F1889B1F44B1D /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Models.swift; path = PetstoreClient/Classes/Swaggers/Models.swift; sourceTree = ""; }; + 30C1E56142D8B120BDDE2AF5CA160E22 /* EnumArrays.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumArrays.swift; sourceTree = ""; }; + 32432BEBC9EDBC5E269C9AA0E570F464 /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; 32B030D27CAC730C5EB0F22390645310 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; - 3581DEB2B2BDC3D8A0BF7C43BD317506 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIs.swift; path = PetstoreClient/Classes/Swaggers/APIs.swift; sourceTree = ""; }; - 3617A5AF85A2814F852C73FD5D575262 /* Model200Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Model200Response.swift; sourceTree = ""; }; - 3B26D25AFB2018A320BA1C7EDE3F560C /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; + 32EFBC701E63AE331BC0BF170B2C1E2B /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; + 33A04B5D27E86AF4B84D95E21CF3F452 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 364DFA113368D39E8F9FF776C3C78B11 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; + 36EB25B2EACD40B282A658DA456B0FED /* Cat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Cat.swift; sourceTree = ""; }; + 374D32747BDC0BDD7ACFF23F5BF910C3 /* AdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AdditionalPropertiesClass.swift; sourceTree = ""; }; + 38F502D93EB2D1D9C2A1283F96BFF4D2 /* MapTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MapTest.swift; sourceTree = ""; }; 3D60BC9955B4F7FFA62D7440CB385C11 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; - 3ED6F43B3A7602CD88ED67B9873B2036 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Models.swift; path = PetstoreClient/Classes/Swaggers/Models.swift; sourceTree = ""; }; - 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; - 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 3FB1FE2028948C532392F549A4356FBC /* MixedPropertiesAndAdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MixedPropertiesAndAdditionalPropertiesClass.swift; sourceTree = ""; }; - 411BB07BE03DCC7000891F6A5E62BBC6 /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = PetstoreClient/Classes/Swaggers/Configuration.swift; sourceTree = ""; }; - 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; - 4530F24A4BDA094563779F1D4313B9E1 /* Cat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Cat.swift; sourceTree = ""; }; - 45CB52E75AED2F044F187FD71FDFC880 /* ArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfNumberOnly.swift; sourceTree = ""; }; - 466D426E7AA31C27ABC601DD606EF126 /* JSONEncodableEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodableEncoding.swift; path = PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift; sourceTree = ""; }; + 3E5EF70E686134181F06537A75BA0FD2 /* OuterEnum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterEnum.swift; sourceTree = ""; }; + 419496CDDD7E7536CBEA02BAEE2C7C21 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 456356DFF7271B4F562B7F04E03E3CA8 /* FakeAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeAPI.swift; sourceTree = ""; }; 46CDAC6C1187C5467E576980E1062C8B /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; - 475EFFB863F38801DE73965C1438E2FF /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; - 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 4A0977DBA9BAE46013DFD65E4400A0CB /* ReadOnlyFirst.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ReadOnlyFirst.swift; sourceTree = ""; }; + 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 49BB1DA804C4AA7D9FEF0DC43604CCCE /* Fake_classname_tags123API.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Fake_classname_tags123API.swift; sourceTree = ""; }; 4AF006B0AD5765D1BFA8253C2DCBB126 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; - 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; - 5AE839994FB9B18B77FC95BCC9594683 /* OuterComposite.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterComposite.swift; sourceTree = ""; }; - 5B8F990A8905B95231C6D1955750D23C /* Client.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Client.swift; sourceTree = ""; }; - 5EB640315A574EA2C8E4584499B31A44 /* OuterString.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterString.swift; sourceTree = ""; }; + 4EB94F5F2FE938ECEA46481E25FFA28F /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; + 4F72B7A542B1D04D38B262F407D0F92F /* SpecialModelName.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SpecialModelName.swift; sourceTree = ""; }; + 51830C53E0E76A54309CE2137E716625 /* AnotherfakeAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AnotherfakeAPI.swift; sourceTree = ""; }; + 55CCB86279C9704891B8B855CA6380F6 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; + 584CE59DFDF2D30A308478C17A426ADA /* ArrayTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayTest.swift; sourceTree = ""; }; + 5EF8BA4CB172F8F6925C18B674169419 /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; + 61D920D6E48023BCBF18CD83450D05F5 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; 6639346628280A0D0FAD35196BF56108 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; 66A46F517F0AF7E85A16D723F6406896 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; - 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; - 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 670103307A767288F991B17974F3E258 /* ApiResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ApiResponse.swift; sourceTree = ""; }; + 697B1649F70C9355E6ED995300DBBA28 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIs.swift; path = PetstoreClient/Classes/Swaggers/APIs.swift; sourceTree = ""; }; + 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_SwaggerClient.framework; path = "Pods-SwaggerClient.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 6CAF4F2E2C16A07E038AAA59349BBCD9 /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireImplementations.swift; path = PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift; sourceTree = ""; }; + 6F80C8976AE5FBE0927AD59150439B97 /* AnimalFarm.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AnimalFarm.swift; sourceTree = ""; }; 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 7417953898146193F86A165CD5F3AF4A /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; - 7C6145F09A87143B7FC501BE989C8BBD /* FakeAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeAPI.swift; sourceTree = ""; }; - 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 7D141D1953E5C6E67E362CE73090E48A /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; - 7EA034E64EC60C1FCC5609CA9962CD51 /* CodableHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CodableHelper.swift; path = PetstoreClient/Classes/Swaggers/CodableHelper.swift; sourceTree = ""; }; - 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; - 854F6A83AC5201A267F39995BF249D32 /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireImplementations.swift; path = PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift; sourceTree = ""; }; - 8689097AED0350F905AFA5B0962FA969 /* Animal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Animal.swift; sourceTree = ""; }; - 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; + 712969C66751DDCC0D484F06819ADFAF /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; + 721957E37E3EE5DB5F8DBF20A032B42A /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; + 76645699475D3AB6EB5242AC4D0CEFAE /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; + 791E26F1F38D683DDDDF5B5A4B3D6607 /* MixedPropertiesAndAdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MixedPropertiesAndAdditionalPropertiesClass.swift; sourceTree = ""; }; + 7DEE2B177461F2E7FC327D113FEC55D4 /* List.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = List.swift; sourceTree = ""; }; + 814471C0F27B39D751143F0CD53670BD /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 828ED4B097AAB98D5568D37B8AECAFD0 /* ClassModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ClassModel.swift; sourceTree = ""; }; + 84B5DCFB56EC99326DEBD055A032458E /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; 87882A1F5A92C8138D54545E51D51E6F /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; - 87DCB85380B2EC22CFE743BEDE7E4114 /* Return.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Return.swift; sourceTree = ""; }; - 88EC57640E276EA2387256530FB1F868 /* EnumArrays.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumArrays.swift; sourceTree = ""; }; - 897799EBBCCE802354256F9E7984C2CF /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; - 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8B87E0BA794A79025212F37D32449C63 /* List.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = List.swift; sourceTree = ""; }; - 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - 9776B33259DFB803A3E6D9573FA3DE3E /* FormatTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FormatTest.swift; sourceTree = ""; }; + 896B006368E7DC47A51391033A97C2EE /* ReadOnlyFirst.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ReadOnlyFirst.swift; sourceTree = ""; }; + 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = PetstoreClient.framework; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8C78CDA7E4BB301D917FE7CFBD2457EF /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIHelper.swift; path = PetstoreClient/Classes/Swaggers/APIHelper.swift; sourceTree = ""; }; + 8E3B882B966B7AF813A56A7DA9DA1F1C /* Name.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Name.swift; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 987E88064EF735B91468D5018C18E261 /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Extensions.swift; path = PetstoreClient/Classes/Swaggers/Extensions.swift; sourceTree = ""; }; + 98A8E010F6244706560DDC29B122EBAF /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + 9D08EC9B39FEBA43A5B55DAF97AAEBE9 /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; + 9D780FDAD16A03CC25F4D6F3317B9423 /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; A01C037B4034EDA3D7955BC5E4E9D9D6 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; - A9930F8E68307FDF3470DAFB398895B2 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIHelper.swift; path = PetstoreClient/Classes/Swaggers/APIHelper.swift; sourceTree = ""; }; + A08C7F48AC7ABF4E88804808C4EB68F1 /* ArrayOfArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfArrayOfNumberOnly.swift; sourceTree = ""; }; + A145777600D2D0E2B9427EEE317DF443 /* FakeClassnameTags123API.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeClassnameTags123API.swift; sourceTree = ""; }; + AC665263E59F937C09C52DBC4851F44F /* OuterNumber.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterNumber.swift; sourceTree = ""; }; + AD15E529B026F88FF8EAE32BD84D468D /* OuterBoolean.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterBoolean.swift; sourceTree = ""; }; + AE8315D9D127E9BAC2C7256DB40D1D6D /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + AF3A2EA92DAC72BC0CED7B12F16198BD /* Model200Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Model200Response.swift; sourceTree = ""; }; B029DBC43E49A740F12B5E4D2E6DD452 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; - B44A27EFBB0DA84D738057B77F3413B1 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; - B5DF7C9C577375BE47CAE380DE3EBE19 /* HasOnlyReadOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HasOnlyReadOnly.swift; sourceTree = ""; }; - BA7C170F1E6A7A846F3D1C4BF9F78EAA /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; - BCCA9CA7D9C1A2047BB93336C5708DFD /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; - BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; - C0C60220F2C965335A15C6C5688ACE4F /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; - C3102957D0FBF5FFA80969BB2A15F8FF /* ApiResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ApiResponse.swift; sourceTree = ""; }; - C3153AF6539569349FDEA90444438B8A /* AdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AdditionalPropertiesClass.swift; sourceTree = ""; }; - C3862A83F9BE857B1E903ABBBDE37EF7 /* AnimalFarm.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AnimalFarm.swift; sourceTree = ""; }; - C3941FB77CA24840ADF5671D16FE460C /* EnumTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumTest.swift; sourceTree = ""; }; - C4B3F69D54C19FC502362EEE3544ECA0 /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; - C7E7932024A79370E61700F5FD439D37 /* SpecialModelName.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SpecialModelName.swift; sourceTree = ""; }; - C925A1EF89E6AF23AE6EA4BA515A6E11 /* ClassModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ClassModel.swift; sourceTree = ""; }; - D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; - D54B91C61FC0918800319969 /* AnotherfakeAPI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnotherfakeAPI.swift; sourceTree = ""; }; - DB3DDF6C3277994828CD09F3155BB74E /* JSONEncodingHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodingHelper.swift; path = PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift; sourceTree = ""; }; - DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; - DF26681AB7FB981F237CD8EA4F059708 /* MapTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MapTest.swift; sourceTree = ""; }; + B28DC9FF9278F92F178AC7F416FBEF3E /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; + B4F28D074D15DD5B49DC39B3706C7C87 /* FormatTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FormatTest.swift; sourceTree = ""; }; + B988BD8876FEE563F8D7A6E2534BA48B /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; + B99164AE8FDE28FAD698B280AC716F77 /* ArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfNumberOnly.swift; sourceTree = ""; }; + BFD9B6C73F406E259D12AAD66EB86E3A /* HasOnlyReadOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HasOnlyReadOnly.swift; sourceTree = ""; }; + C26CC9E49237A04F52DC71125A1756AB /* Client.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Client.swift; sourceTree = ""; }; + C3036A4C6739CD7F9D802133405FB095 /* NumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NumberOnly.swift; sourceTree = ""; }; + C9F529192DED719D7A55A3E804866F26 /* OuterComposite.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterComposite.swift; sourceTree = ""; }; + CAF6F32F117197F6F08B477687F09728 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; + CF1ECC5499BE9BF36F0AE0CE47ABB673 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; + CFA4F581E074596AB5C3DAF3D9C39F17 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; + D1F50F37DFB6DC0B7B9D8C373E5A3EAE /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + D47B812D78D0AE64D85D16A96840F8C4 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; + D752057107F19596D3B8EA574206B2F2 /* OuterString.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterString.swift; sourceTree = ""; }; DFCB8C44DE758E906C0BCDA455937B85 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; - E0A482A15F21B4BC206B31E7A0FAB79F /* Capitalization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Capitalization.swift; sourceTree = ""; }; - E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; - E1FF93AC280A80800873A20A8F72AD29 /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; + E28B79A691A2192E2A8595ACB60CC54C /* Dog.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Dog.swift; sourceTree = ""; }; E2F9510473F6FFD7AA66524DB16C2263 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; - E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; E5A8AA5F9EDED0A0BDDE7E830BF4AEE0 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; - E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; - EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - EB834CA4A0478028D959D9EBD119D953 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - F05D3E8C18F8C0EF732558438FAA421A /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Extensions.swift; path = PetstoreClient/Classes/Swaggers/Extensions.swift; sourceTree = ""; }; - F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; - FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; - FE7B50737921DC202987A0E4A1665B90 /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + E5EB60B9D147E1DCD36D55283254A515 /* JSONEncodableEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodableEncoding.swift; path = PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift; sourceTree = ""; }; + EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_SwaggerClientTests.framework; path = "Pods-SwaggerClientTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + EC6A834DBFB72DAA5CF0C32268CDF605 /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = PetstoreClient/Classes/Swaggers/Configuration.swift; sourceTree = ""; }; + F1ED5AD8A7A28479CDC87C72B75010ED /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + F388A1ADD212030D9542E86628F22BD6 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; + F3E1116FA9F9F3AFD9332B7236F6E711 /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; + F46B1129B323D17632F7089F71632F60 /* JSONEncodingHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodingHelper.swift; path = PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift; sourceTree = ""; }; + F4BB3B2146310CA18C30F145BFF15BD9 /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; + F8FCC3BC0A0823C3FF68C4E1EF67B2FD /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; + FB0F6DF945AB4286D73C45A2139ED7B3 /* Return.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Return.swift; sourceTree = ""; }; + FC15A6FFC961DC8B56D9DD9150014C38 /* PetstoreClient.podspec */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; path = PetstoreClient.podspec; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + FD18CDAD22507BB2C69589FD60138F66 /* Capitalization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Capitalization.swift; sourceTree = ""; }; + FDBB687EF1CAF131DB3DDD99AAE54AB6 /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + FF4FEED941249256FD7E23C19D4567AC /* EnumClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumClass.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 2D7583F1D86C34DDA26383E3BD322469 /* Frameworks */ = { + 87AF7EC7404199AC8C5D22375A6059BF /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 96179D2776662CFF1D8CD2BA7599E165 /* Alamofire.framework in Frameworks */, - 73BF6D173C637DEE9571E96E19EADABD /* Foundation.framework in Frameworks */, + E723EED99F633C8620915572700A2D2E /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; - 87AF7EC7404199AC8C5D22375A6059BF /* Frameworks */ = { + 8F986B6660A23551BF1713A47F9B5752 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - E723EED99F633C8620915572700A2D2E /* Foundation.framework in Frameworks */, + DD24D51FC8B3C4AE95827418EC5D5EF3 /* Alamofire.framework in Frameworks */, + F8D1A2541DD038CBD649F825DBD1DF63 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -261,6 +264,20 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 1638B55794AEC03168E0A73BFA054478 /* Support Files */ = { + isa = PBXGroup; + children = ( + 1E9A49B1D85B7A38F2CAD05F245B27C3 /* Info.plist */, + 19CFD6BC7040A5BC22831D4B5EB7F793 /* PetstoreClient.modulemap */, + F1ED5AD8A7A28479CDC87C72B75010ED /* PetstoreClient.xcconfig */, + 0467D138A3101545CABA11DDD745B87B /* PetstoreClient-dummy.m */, + B28DC9FF9278F92F178AC7F416FBEF3E /* PetstoreClient-prefix.pch */, + 55CCB86279C9704891B8B855CA6380F6 /* PetstoreClient-umbrella.h */, + ); + name = "Support Files"; + path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; + sourceTree = ""; + }; 200D10EB20F0397D47F022B50CF0433F /* Alamofire */ = { isa = PBXGroup; children = ( @@ -281,83 +298,100 @@ A01C037B4034EDA3D7955BC5E4E9D9D6 /* TaskDelegate.swift */, 87882A1F5A92C8138D54545E51D51E6F /* Timeline.swift */, B029DBC43E49A740F12B5E4D2E6DD452 /* Validation.swift */, - 55F14F994FE7AB51F028BFE66CEF3106 /* Support Files */, + 2E5925946A4DE3B8F7E4137BACAD9618 /* Support Files */, ); + name = Alamofire; path = Alamofire; sourceTree = ""; }; - 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */ = { - isa = PBXGroup; - children = ( - 200D10EB20F0397D47F022B50CF0433F /* Alamofire */, - ); - name = Pods; - sourceTree = ""; - }; - 51A9B78D6A7E7FB5A465754528750815 /* iOS */ = { + 2E5925946A4DE3B8F7E4137BACAD9618 /* Support Files */ = { isa = PBXGroup; children = ( - 0D0533E4EC2277AAAC8888328EC5A64B /* Foundation.framework */, + 210971763CB2FC0DC4E378271A37BE32 /* Alamofire.modulemap */, + 33A04B5D27E86AF4B84D95E21CF3F452 /* Alamofire.xcconfig */, + D1F50F37DFB6DC0B7B9D8C373E5A3EAE /* Alamofire-dummy.m */, + 61D920D6E48023BCBF18CD83450D05F5 /* Alamofire-prefix.pch */, + 03DECE84DC850B04690604AB7C521277 /* Alamofire-umbrella.h */, + 117EFB31D9AD9673BAF51B48596F19E2 /* Info.plist */, ); - name = iOS; + name = "Support Files"; + path = "../Target Support Files/Alamofire"; sourceTree = ""; }; - 55F14F994FE7AB51F028BFE66CEF3106 /* Support Files */ = { + 325E314AD76E8F3FF0B03E2401003FC5 /* Models */ = { isa = PBXGroup; children = ( - 7D141D1953E5C6E67E362CE73090E48A /* Alamofire.modulemap */, - E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */, - 22C1C119BCE81C53F76CAC2BE27C38E0 /* Alamofire-dummy.m */, - BCCA9CA7D9C1A2047BB93336C5708DFD /* Alamofire-prefix.pch */, - B44A27EFBB0DA84D738057B77F3413B1 /* Alamofire-umbrella.h */, - 13A0A663B36A229C69D5274A83E93F88 /* Info.plist */, + 374D32747BDC0BDD7ACFF23F5BF910C3 /* AdditionalPropertiesClass.swift */, + 171602313BBD5AE0D5F50FFB70A96CED /* Animal.swift */, + 6F80C8976AE5FBE0927AD59150439B97 /* AnimalFarm.swift */, + 670103307A767288F991B17974F3E258 /* ApiResponse.swift */, + A08C7F48AC7ABF4E88804808C4EB68F1 /* ArrayOfArrayOfNumberOnly.swift */, + B99164AE8FDE28FAD698B280AC716F77 /* ArrayOfNumberOnly.swift */, + 584CE59DFDF2D30A308478C17A426ADA /* ArrayTest.swift */, + FD18CDAD22507BB2C69589FD60138F66 /* Capitalization.swift */, + 36EB25B2EACD40B282A658DA456B0FED /* Cat.swift */, + 84B5DCFB56EC99326DEBD055A032458E /* Category.swift */, + 828ED4B097AAB98D5568D37B8AECAFD0 /* ClassModel.swift */, + C26CC9E49237A04F52DC71125A1756AB /* Client.swift */, + E28B79A691A2192E2A8595ACB60CC54C /* Dog.swift */, + 30C1E56142D8B120BDDE2AF5CA160E22 /* EnumArrays.swift */, + FF4FEED941249256FD7E23C19D4567AC /* EnumClass.swift */, + 289EF031EA3B2CA318F7EACE05641165 /* EnumTest.swift */, + B4F28D074D15DD5B49DC39B3706C7C87 /* FormatTest.swift */, + BFD9B6C73F406E259D12AAD66EB86E3A /* HasOnlyReadOnly.swift */, + 7DEE2B177461F2E7FC327D113FEC55D4 /* List.swift */, + 38F502D93EB2D1D9C2A1283F96BFF4D2 /* MapTest.swift */, + 791E26F1F38D683DDDDF5B5A4B3D6607 /* MixedPropertiesAndAdditionalPropertiesClass.swift */, + AF3A2EA92DAC72BC0CED7B12F16198BD /* Model200Response.swift */, + 8E3B882B966B7AF813A56A7DA9DA1F1C /* Name.swift */, + C3036A4C6739CD7F9D802133405FB095 /* NumberOnly.swift */, + 4EB94F5F2FE938ECEA46481E25FFA28F /* Order.swift */, + AD15E529B026F88FF8EAE32BD84D468D /* OuterBoolean.swift */, + C9F529192DED719D7A55A3E804866F26 /* OuterComposite.swift */, + 3E5EF70E686134181F06537A75BA0FD2 /* OuterEnum.swift */, + AC665263E59F937C09C52DBC4851F44F /* OuterNumber.swift */, + D752057107F19596D3B8EA574206B2F2 /* OuterString.swift */, + 5EF8BA4CB172F8F6925C18B674169419 /* Pet.swift */, + 896B006368E7DC47A51391033A97C2EE /* ReadOnlyFirst.swift */, + FB0F6DF945AB4286D73C45A2139ED7B3 /* Return.swift */, + 4F72B7A542B1D04D38B262F407D0F92F /* SpecialModelName.swift */, + B988BD8876FEE563F8D7A6E2534BA48B /* Tag.swift */, + 32EFBC701E63AE331BC0BF170B2C1E2B /* User.swift */, ); - name = "Support Files"; - path = "../Target Support Files/Alamofire"; + name = Models; + path = PetstoreClient/Classes/Swaggers/Models; sourceTree = ""; }; - 59B91F212518421F271EBA85D5530651 /* Frameworks */ = { + 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */ = { isa = PBXGroup; children = ( - 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */, - 51A9B78D6A7E7FB5A465754528750815 /* iOS */, + 200D10EB20F0397D47F022B50CF0433F /* Alamofire */, ); - name = Frameworks; + name = Pods; sourceTree = ""; }; - 60558172C46150B1CC244DFD7F495889 /* Support Files */ = { + 51A9B78D6A7E7FB5A465754528750815 /* iOS */ = { isa = PBXGroup; children = ( - EB834CA4A0478028D959D9EBD119D953 /* Info.plist */, - 2ACC287E45C0FCE8717A34B8ECA88A30 /* PetstoreClient.modulemap */, - FE7B50737921DC202987A0E4A1665B90 /* PetstoreClient.xcconfig */, - 3B26D25AFB2018A320BA1C7EDE3F560C /* PetstoreClient-dummy.m */, - BA7C170F1E6A7A846F3D1C4BF9F78EAA /* PetstoreClient-prefix.pch */, - C0C60220F2C965335A15C6C5688ACE4F /* PetstoreClient-umbrella.h */, + 0D0533E4EC2277AAAC8888328EC5A64B /* Foundation.framework */, ); - name = "Support Files"; - path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; + name = iOS; sourceTree = ""; }; - 7C3C4943F0B3A9E87CCF23AA96272CB5 /* APIs */ = { + 59B91F212518421F271EBA85D5530651 /* Frameworks */ = { isa = PBXGroup; children = ( - D54B91C61FC0918800319969 /* AnotherfakeAPI.swift */, - 2AE3690E05FA4B6B3A8600FCA1631D8C /* FakeClassnameTags123API.swift */, - 7C6145F09A87143B7FC501BE989C8BBD /* FakeAPI.swift */, - 475EFFB863F38801DE73965C1438E2FF /* PetAPI.swift */, - 897799EBBCCE802354256F9E7984C2CF /* StoreAPI.swift */, - 158D0513D0844E7FE6AEFAEE70E88618 /* UserAPI.swift */, + 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */, + 51A9B78D6A7E7FB5A465754528750815 /* iOS */, ); - name = APIs; - path = PetstoreClient/Classes/Swaggers/APIs; + name = Frameworks; sourceTree = ""; }; 7DB346D0F39D3F0E887471402A8071AB = { isa = PBXGroup; children = ( 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, - EDE36CDEEF568DD818B58A28C3C0DA80 /* Development Pods */, + EC52080E65FE34CBDE5F694B08BA9836 /* Development Pods */, 59B91F212518421F271EBA85D5530651 /* Frameworks */, 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */, 9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */, @@ -365,44 +399,27 @@ ); sourceTree = ""; }; - 80845DB4F55E7613E45819034AAA6B0F /* PetstoreClient */ = { + 9552BC9D547079722BECEF69D39F81A1 /* PetstoreClient */ = { isa = PBXGroup; children = ( - 854F6A83AC5201A267F39995BF249D32 /* AlamofireImplementations.swift */, - A9930F8E68307FDF3470DAFB398895B2 /* APIHelper.swift */, - 3581DEB2B2BDC3D8A0BF7C43BD317506 /* APIs.swift */, - 7EA034E64EC60C1FCC5609CA9962CD51 /* CodableHelper.swift */, - 411BB07BE03DCC7000891F6A5E62BBC6 /* Configuration.swift */, - F05D3E8C18F8C0EF732558438FAA421A /* Extensions.swift */, - 466D426E7AA31C27ABC601DD606EF126 /* JSONEncodableEncoding.swift */, - DB3DDF6C3277994828CD09F3155BB74E /* JSONEncodingHelper.swift */, - 3ED6F43B3A7602CD88ED67B9873B2036 /* Models.swift */, - 7C3C4943F0B3A9E87CCF23AA96272CB5 /* APIs */, - B7C7CFA5065F490C632218EDF496EB25 /* Models */, - 60558172C46150B1CC244DFD7F495889 /* Support Files */, + 6CAF4F2E2C16A07E038AAA59349BBCD9 /* AlamofireImplementations.swift */, + 8C78CDA7E4BB301D917FE7CFBD2457EF /* APIHelper.swift */, + 697B1649F70C9355E6ED995300DBBA28 /* APIs.swift */, + 06D5E6CDDEE294F817C22C521B562508 /* CodableHelper.swift */, + EC6A834DBFB72DAA5CF0C32268CDF605 /* Configuration.swift */, + 987E88064EF735B91468D5018C18E261 /* Extensions.swift */, + E5EB60B9D147E1DCD36D55283254A515 /* JSONEncodableEncoding.swift */, + F46B1129B323D17632F7089F71632F60 /* JSONEncodingHelper.swift */, + 2AEE7AA4D6A19965503F1889B1F44B1D /* Models.swift */, + C6898391DC18DA3449C18CD93A69078D /* APIs */, + 325E314AD76E8F3FF0B03E2401003FC5 /* Models */, + D313744EEA7BEA6ED6344DEF771433F5 /* Pod */, + 1638B55794AEC03168E0A73BFA054478 /* Support Files */, ); name = PetstoreClient; path = ../..; sourceTree = ""; }; - 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */ = { - isa = PBXGroup; - children = ( - 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */, - DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */, - 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */, - E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */, - 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */, - BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */, - D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */, - 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */, - 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */, - 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */, - ); - name = "Pods-SwaggerClient"; - path = "Target Support Files/Pods-SwaggerClient"; - sourceTree = ""; - }; 9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */ = { isa = PBXGroup; children = ( @@ -414,81 +431,78 @@ name = Products; sourceTree = ""; }; - B7C7CFA5065F490C632218EDF496EB25 /* Models */ = { + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { isa = PBXGroup; children = ( - C3153AF6539569349FDEA90444438B8A /* AdditionalPropertiesClass.swift */, - 8689097AED0350F905AFA5B0962FA969 /* Animal.swift */, - C3862A83F9BE857B1E903ABBBDE37EF7 /* AnimalFarm.swift */, - C3102957D0FBF5FFA80969BB2A15F8FF /* ApiResponse.swift */, - 1B900B675208453FB7767B0D97D50932 /* ArrayOfArrayOfNumberOnly.swift */, - 45CB52E75AED2F044F187FD71FDFC880 /* ArrayOfNumberOnly.swift */, - 30B827D77F92D24E6D24561F491F2A50 /* ArrayTest.swift */, - E0A482A15F21B4BC206B31E7A0FAB79F /* Capitalization.swift */, - 4530F24A4BDA094563779F1D4313B9E1 /* Cat.swift */, - 7417953898146193F86A165CD5F3AF4A /* Category.swift */, - C925A1EF89E6AF23AE6EA4BA515A6E11 /* ClassModel.swift */, - 5B8F990A8905B95231C6D1955750D23C /* Client.swift */, - 28F73294B64CD8821EC2467CB7F1F073 /* Dog.swift */, - 88EC57640E276EA2387256530FB1F868 /* EnumArrays.swift */, - 30E08D3E06CED1E4F2876EFA44A239ED /* EnumClass.swift */, - C3941FB77CA24840ADF5671D16FE460C /* EnumTest.swift */, - 9776B33259DFB803A3E6D9573FA3DE3E /* FormatTest.swift */, - B5DF7C9C577375BE47CAE380DE3EBE19 /* HasOnlyReadOnly.swift */, - 8B87E0BA794A79025212F37D32449C63 /* List.swift */, - DF26681AB7FB981F237CD8EA4F059708 /* MapTest.swift */, - 3FB1FE2028948C532392F549A4356FBC /* MixedPropertiesAndAdditionalPropertiesClass.swift */, - 3617A5AF85A2814F852C73FD5D575262 /* Model200Response.swift */, - 2C0EF68B5117187E979D1DE4ECDB938E /* Name.swift */, - 2A332587F10679E262455F979B3D1055 /* NumberOnly.swift */, - 24D3039E712D1279434152E805AEDA65 /* Order.swift */, - 21A143975CF52EBFEF79A307CC7CB00E /* OuterBoolean.swift */, - 5AE839994FB9B18B77FC95BCC9594683 /* OuterComposite.swift */, - 13C6EEF1D81A0C523AE569F1732AC8DC /* OuterEnum.swift */, - 0BA93068A5B18A779CC9B0FC3F685400 /* OuterNumber.swift */, - 5EB640315A574EA2C8E4584499B31A44 /* OuterString.swift */, - E1FF93AC280A80800873A20A8F72AD29 /* Pet.swift */, - 4A0977DBA9BAE46013DFD65E4400A0CB /* ReadOnlyFirst.swift */, - 87DCB85380B2EC22CFE743BEDE7E4114 /* Return.swift */, - C7E7932024A79370E61700F5FD439D37 /* SpecialModelName.swift */, - 02E62B78D97471D708B23605FCAA9EA1 /* Tag.swift */, - C4B3F69D54C19FC502362EEE3544ECA0 /* User.swift */, + DE503BFFEBBF78BDC743C8A6A50DFF47 /* Pods-SwaggerClient */, + E9EDF70990CC7A4463ED5FC2E3719BD0 /* Pods-SwaggerClientTests */, ); - name = Models; - path = PetstoreClient/Classes/Swaggers/Models; + name = "Targets Support Files"; sourceTree = ""; }; - C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { + C6898391DC18DA3449C18CD93A69078D /* APIs */ = { isa = PBXGroup; children = ( - 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */, - D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */, + 51830C53E0E76A54309CE2137E716625 /* AnotherfakeAPI.swift */, + 49BB1DA804C4AA7D9FEF0DC43604CCCE /* Fake_classname_tags123API.swift */, + 456356DFF7271B4F562B7F04E03E3CA8 /* FakeAPI.swift */, + A145777600D2D0E2B9427EEE317DF443 /* FakeClassnameTags123API.swift */, + 712969C66751DDCC0D484F06819ADFAF /* PetAPI.swift */, + 98A8E010F6244706560DDC29B122EBAF /* StoreAPI.swift */, + 364DFA113368D39E8F9FF776C3C78B11 /* UserAPI.swift */, ); - name = "Targets Support Files"; + name = APIs; + path = PetstoreClient/Classes/Swaggers/APIs; + sourceTree = ""; + }; + D313744EEA7BEA6ED6344DEF771433F5 /* Pod */ = { + isa = PBXGroup; + children = ( + FC15A6FFC961DC8B56D9DD9150014C38 /* PetstoreClient.podspec */, + ); + name = Pod; sourceTree = ""; }; - D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */ = { + DE503BFFEBBF78BDC743C8A6A50DFF47 /* Pods-SwaggerClient */ = { isa = PBXGroup; children = ( - 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */, - 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */, - FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */, - 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */, - 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */, - 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */, - E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */, - F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */, - 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */, - 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */, + 814471C0F27B39D751143F0CD53670BD /* Info.plist */, + CFA4F581E074596AB5C3DAF3D9C39F17 /* Pods-SwaggerClient.modulemap */, + 76645699475D3AB6EB5242AC4D0CEFAE /* Pods-SwaggerClient-acknowledgements.markdown */, + 08BDFE9C9E9365771FF2D47928E3E79A /* Pods-SwaggerClient-acknowledgements.plist */, + F8FCC3BC0A0823C3FF68C4E1EF67B2FD /* Pods-SwaggerClient-dummy.m */, + 0AD61F8554C909A3AFA66AD9ECCB5F23 /* Pods-SwaggerClient-frameworks.sh */, + F4BB3B2146310CA18C30F145BFF15BD9 /* Pods-SwaggerClient-resources.sh */, + 32432BEBC9EDBC5E269C9AA0E570F464 /* Pods-SwaggerClient-umbrella.h */, + AE8315D9D127E9BAC2C7256DB40D1D6D /* Pods-SwaggerClient.debug.xcconfig */, + F388A1ADD212030D9542E86628F22BD6 /* Pods-SwaggerClient.release.xcconfig */, + ); + name = "Pods-SwaggerClient"; + path = "Target Support Files/Pods-SwaggerClient"; + sourceTree = ""; + }; + E9EDF70990CC7A4463ED5FC2E3719BD0 /* Pods-SwaggerClientTests */ = { + isa = PBXGroup; + children = ( + 419496CDDD7E7536CBEA02BAEE2C7C21 /* Info.plist */, + 9D08EC9B39FEBA43A5B55DAF97AAEBE9 /* Pods-SwaggerClientTests.modulemap */, + D47B812D78D0AE64D85D16A96840F8C4 /* Pods-SwaggerClientTests-acknowledgements.markdown */, + 9D780FDAD16A03CC25F4D6F3317B9423 /* Pods-SwaggerClientTests-acknowledgements.plist */, + 721957E37E3EE5DB5F8DBF20A032B42A /* Pods-SwaggerClientTests-dummy.m */, + CAF6F32F117197F6F08B477687F09728 /* Pods-SwaggerClientTests-frameworks.sh */, + F3E1116FA9F9F3AFD9332B7236F6E711 /* Pods-SwaggerClientTests-resources.sh */, + CF1ECC5499BE9BF36F0AE0CE47ABB673 /* Pods-SwaggerClientTests-umbrella.h */, + 1ACCB3378E1513AEAADC85C4036257E4 /* Pods-SwaggerClientTests.debug.xcconfig */, + FDBB687EF1CAF131DB3DDD99AAE54AB6 /* Pods-SwaggerClientTests.release.xcconfig */, ); name = "Pods-SwaggerClientTests"; path = "Target Support Files/Pods-SwaggerClientTests"; sourceTree = ""; }; - EDE36CDEEF568DD818B58A28C3C0DA80 /* Development Pods */ = { + EC52080E65FE34CBDE5F694B08BA9836 /* Development Pods */ = { isa = PBXGroup; children = ( - 80845DB4F55E7613E45819034AAA6B0F /* PetstoreClient */, + 9552BC9D547079722BECEF69D39F81A1 /* PetstoreClient */, ); name = "Development Pods"; sourceTree = ""; @@ -504,19 +518,19 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 977FD2449A760A426BC92AD40BF0FAE9 /* Headers */ = { + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 9067B627206EA4FFE8E94388031FBB70 /* PetstoreClient-umbrella.h in Headers */, + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { + BD12918CEA9299E11B49061B4FC1F33A /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, + C40D07E49370F6A2B17F2AA7D8B5B8A5 /* PetstoreClient-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -550,39 +564,39 @@ productReference = 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */; productType = "com.apple.product-type.framework"; }; - 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { + 691AAEA1153824FE132C368C2B9D4ECF /* PetstoreClient */ = { isa = PBXNativeTarget; - buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildConfigurationList = C82540F432F75C90F90C570A5CBBF5CA /* Build configuration list for PBXNativeTarget "PetstoreClient" */; buildPhases = ( - 32B9974868188C4803318E36329C87FE /* Sources */, - 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, - B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, + CAF46E0F878E8B81DD1A04BCA960D71B /* Sources */, + 8F986B6660A23551BF1713A47F9B5752 /* Frameworks */, + BD12918CEA9299E11B49061B4FC1F33A /* Headers */, ); buildRules = ( ); dependencies = ( + F4B10CB4F7BF2C0DF6CDAFF8DA9F03B4 /* PBXTargetDependency */, ); - name = Alamofire; - productName = Alamofire; - productReference = 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */; + name = PetstoreClient; + productName = PetstoreClient; + productReference = 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */; productType = "com.apple.product-type.framework"; }; - F273DBB2E19E2286018971F2B25DEB52 /* PetstoreClient */ = { + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { isa = PBXNativeTarget; - buildConfigurationList = 0E45B203539274106092021633F5C54E /* Build configuration list for PBXNativeTarget "PetstoreClient" */; + buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; buildPhases = ( - CCAD31695209FE4A1313C16F1B7A220D /* Sources */, - 2D7583F1D86C34DDA26383E3BD322469 /* Frameworks */, - 977FD2449A760A426BC92AD40BF0FAE9 /* Headers */, + 32B9974868188C4803318E36329C87FE /* Sources */, + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, ); buildRules = ( ); dependencies = ( - 14D50D2534F42D5E57F9341C234C9364 /* PBXTargetDependency */, ); - name = PetstoreClient; - productName = PetstoreClient; - productReference = 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */; + name = Alamofire; + productName = Alamofire; + productReference = 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */; productType = "com.apple.product-type.framework"; }; F3DF8DD6DBDCB07B04D7B1CC8A462562 /* Pods-SwaggerClientTests */ = { @@ -608,8 +622,8 @@ D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { isa = PBXProject; attributes = { - LastSwiftUpdateCheck = 0830; - LastUpgradeCheck = 0700; + LastSwiftUpdateCheck = 0930; + LastUpgradeCheck = 0930; }; buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; compatibilityVersion = "Xcode 3.2"; @@ -624,7 +638,7 @@ projectRoot = ""; targets = ( 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, - F273DBB2E19E2286018971F2B25DEB52 /* PetstoreClient */, + 691AAEA1153824FE132C368C2B9D4ECF /* PetstoreClient */, 41903051A113E887E262FB29130EB187 /* Pods-SwaggerClient */, F3DF8DD6DBDCB07B04D7B1CC8A462562 /* Pods-SwaggerClientTests */, ); @@ -673,78 +687,73 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - CCAD31695209FE4A1313C16F1B7A220D /* Sources */ = { + CAF46E0F878E8B81DD1A04BCA960D71B /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 2B1BE5C3FED4683F31A1DA3E4D4FE6C6 /* AdditionalPropertiesClass.swift in Sources */, - 82F7587E619353285C601A5677961853 /* AlamofireImplementations.swift in Sources */, - B384569B4208ADC0A68233491ED19609 /* Animal.swift in Sources */, - 3E11073F08C80332AEFC3A10FC489313 /* AnimalFarm.swift in Sources */, - 2D208564DFB2C2849316BD87AA3F53AC /* APIHelper.swift in Sources */, - DE8F9190013C0FECA7C3413F214B2BAB /* ApiResponse.swift in Sources */, - 9F4FF785FA604AD3A70C4B87FA0ED450 /* APIs.swift in Sources */, - 74E60841671B65510C2E9DBD34EDD96B /* ArrayOfArrayOfNumberOnly.swift in Sources */, - E0C687FEA77962F5E1CE2D4347246984 /* ArrayOfNumberOnly.swift in Sources */, - B4D9507C3602C7D37EB6F7B88269CD52 /* ArrayTest.swift in Sources */, - E0B2924D681BAA663ADE94DC43706E3D /* Capitalization.swift in Sources */, - 90D416A6F921DADEF05F65AFF7E1E5B0 /* Cat.swift in Sources */, - 4814A739814A3809C4D9C61F96012C62 /* Category.swift in Sources */, - 2B22A023463A6CF04BB1BFF869D30AC6 /* ClassModel.swift in Sources */, - F81E110F1F9AAD6C448DCF5DF99C2F41 /* Client.swift in Sources */, - 3B0E9022805FED1731E3C6474C700253 /* CodableHelper.swift in Sources */, - 5E38839B97A3FB54831CB0CE3B177E06 /* Configuration.swift in Sources */, - E6A0A5C14D3633FFE1551CFDE39FA4C3 /* Dog.swift in Sources */, - 0F662FA5B2EB748EA516B8C83742DE29 /* EnumArrays.swift in Sources */, - 9145FC4EDCAF00080761172112D6B4E1 /* EnumClass.swift in Sources */, - 1982792C8B5D5B4999228D16CDBE3E28 /* EnumTest.swift in Sources */, - B65AABE5C7EB03365333C4783B36CCDC /* Extensions.swift in Sources */, - 472DF233EF1CA028A52DB57F87A5687F /* FakeClassnameTags123API.swift in Sources */, - 7EE07906770CB8D69F00429072D7DC02 /* FakeAPI.swift in Sources */, - 4CBD58C64013924FB5A74A106D838285 /* FormatTest.swift in Sources */, - F9884BC36100EA0FC9AAABAC5D4A0371 /* HasOnlyReadOnly.swift in Sources */, - 8158ED5AEE2D6FE60EBA456F691D823C /* JSONEncodableEncoding.swift in Sources */, - AAEFA9B66A1EE281AA8D76AC0DCA3C97 /* JSONEncodingHelper.swift in Sources */, - BA15A21EB63AC8A5B7B859AC8D6E7B23 /* List.swift in Sources */, - 9B73E49DCB45F1F471FA4DE8264BA512 /* MapTest.swift in Sources */, - EDFB99BED377CAB8D24E0256E1208BD1 /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */, - 973AF350C705E18926C330359F0DAC29 /* Model200Response.swift in Sources */, - 24F9EAC555D87891496C9873A3A353BC /* Models.swift in Sources */, - 55F9C83CA76F9B2DA873122BEC278855 /* Name.swift in Sources */, - 7A854DC997BF3D7E3449FF58278EC967 /* NumberOnly.swift in Sources */, - 363930DE8DE4B17D8EF901F5C249A9AC /* Order.swift in Sources */, - D54B91C71FC0918800319969 /* AnotherfakeAPI.swift in Sources */, - F1ACDB1E74FDDF4609EA027BB6D5C9D8 /* OuterBoolean.swift in Sources */, - 707F832EEA6E7DD274201962E4D85B5B /* OuterComposite.swift in Sources */, - CA6B474618AA720ABFB571F69B227AF7 /* OuterEnum.swift in Sources */, - EA063534695F7232C7E7FF9C5A61483A /* OuterNumber.swift in Sources */, - A0F161A5D21EFF05B0208B7C1B6C3C67 /* OuterString.swift in Sources */, - E05C5957E89CE7129CC4880299444A81 /* Pet.swift in Sources */, - 8A4C36FD6B751F6F87BFC6C4E01DD793 /* PetAPI.swift in Sources */, - 7D99F1CDFA55B21CBDB1603DA46C0599 /* PetstoreClient-dummy.m in Sources */, - 5EC075C471A4F4D9A43857B8629D95EE /* ReadOnlyFirst.swift in Sources */, - C888F5D0484D08C3F110B48DF18DDFD6 /* Return.swift in Sources */, - 281150C5E93967FEA2D3921AEC92BA3D /* SpecialModelName.swift in Sources */, - 127354085F10006D6B57C16D3AE2E043 /* StoreAPI.swift in Sources */, - 857A7B68378E7164FD99F549C092436E /* Tag.swift in Sources */, - 4DF5B60FEFEAC2BA370EE79D2567B3E9 /* User.swift in Sources */, - 39C0CB11CA9812CD5BB73A893D27BEE9 /* UserAPI.swift in Sources */, + 46899B04EA5D619054AACDD9C5F2F7B5 /* AdditionalPropertiesClass.swift in Sources */, + 0D2084CADDB0230A4CAF2C0605F828DF /* AlamofireImplementations.swift in Sources */, + CB9A39C25CA7ED02B7E02B5AA1354911 /* Animal.swift in Sources */, + E661B7CF775527BE72A5B2D4EB5F73E8 /* AnimalFarm.swift in Sources */, + 55013BF8F5D5A6B238473A65819BA91E /* AnotherfakeAPI.swift in Sources */, + 04B6872F088373A5D9622389D44ABFA7 /* APIHelper.swift in Sources */, + E0FC0F7FCAAFB628D17EB6277E6384D0 /* ApiResponse.swift in Sources */, + 07EEC7822D7CB95755A6BB464B2BF1D1 /* APIs.swift in Sources */, + 9D4858FD9A6340A4609BEBDF00C382F9 /* ArrayOfArrayOfNumberOnly.swift in Sources */, + D0FF9ABBD288F188E54D3CAB5208202B /* ArrayOfNumberOnly.swift in Sources */, + DA774D60BA836CC50DCEF3F0402A0D25 /* ArrayTest.swift in Sources */, + 28832E8D2FFAF4A8A372893866A96CD3 /* Capitalization.swift in Sources */, + 52661A921B6F46145CE16E108CA3C1CD /* Cat.swift in Sources */, + BCFCE38A7F2EBB043C581F2A24947FEA /* Category.swift in Sources */, + 84FCC3BCB6219E32B67168629345B43F /* ClassModel.swift in Sources */, + B116548930626181CC1301D0ADE31720 /* Client.swift in Sources */, + E0559707E3DAE5B759A2570EE64AEF37 /* CodableHelper.swift in Sources */, + 8106FA532C222AE698AF0D473D8C9160 /* Configuration.swift in Sources */, + BCBC0EA84005299246354BB70B11301B /* Dog.swift in Sources */, + 5C76B11759683109F447BA67F28F83DC /* EnumArrays.swift in Sources */, + 2361B453C0E27F769982D2E157DFD27B /* EnumClass.swift in Sources */, + F88A1839757ADAA76A5A40A3149E5B45 /* EnumTest.swift in Sources */, + BF7DF71571E51EBF9CF76436ADA68ACA /* Extensions.swift in Sources */, + 3EDE1BCF1CAE7C657EA278797CA70181 /* Fake_classname_tags123API.swift in Sources */, + 450A1F9D9F0C0316DC5571EAD3C7FFB6 /* FakeAPI.swift in Sources */, + 3185145561047965FB52DD80ED69B7C8 /* FakeClassnameTags123API.swift in Sources */, + F3728DB3E73B9E46DCCD1FBB17888A31 /* FormatTest.swift in Sources */, + 1271FFC6225DD34662309214506624E3 /* HasOnlyReadOnly.swift in Sources */, + CC1ABC7D57D24128BCE892C928EB155D /* JSONEncodableEncoding.swift in Sources */, + 27AFC4AEBB1B56DD719675A2118CCB8D /* JSONEncodingHelper.swift in Sources */, + 36E58F38207F15EBD91ADCEF62C7C85E /* List.swift in Sources */, + 5F18574D9A8C0B088105A657C4EBFE8A /* MapTest.swift in Sources */, + E7ADAAB656F28A756189B278B28D0099 /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */, + BD15F885C0DB08C2BA875B3A36DFD778 /* Model200Response.swift in Sources */, + 6FD39FEAAFE27DBC3EC0F11B20D97734 /* Models.swift in Sources */, + 749396546BA912EA0DD0A0A38FDEDAA4 /* Name.swift in Sources */, + 31B8C21D76FE98AE41B88A44169ECE84 /* NumberOnly.swift in Sources */, + D0FD45C03A13220C2DEC62BE2330FC92 /* Order.swift in Sources */, + B13CE8FE8573C0FB07C97D0C34DD9CF4 /* OuterBoolean.swift in Sources */, + C7DAA30310B69C6742610B5EBC23B328 /* OuterComposite.swift in Sources */, + 3322B46E9D9AFB13466804547F6404A4 /* OuterEnum.swift in Sources */, + A0AD98559666C4BA8E74CA46211B44F2 /* OuterNumber.swift in Sources */, + 9BD5D264F2B563611262E196A5961066 /* OuterString.swift in Sources */, + 229E82D3A37D202BFF958E8278C2E5D0 /* Pet.swift in Sources */, + A57FEBD11E8DC63EF939F8183779BECA /* PetAPI.swift in Sources */, + F8CBD4B50C45BCC72F66D919E4E37F6A /* PetstoreClient-dummy.m in Sources */, + 36505FE5A99837291C843D5627689950 /* ReadOnlyFirst.swift in Sources */, + 862F16E17E79FAA53D395CE275546D28 /* Return.swift in Sources */, + F4749A9FA396C6C94CF4F4D16897A60C /* SpecialModelName.swift in Sources */, + 802D6A4D73A1A03F0F30D814126EC859 /* StoreAPI.swift in Sources */, + F7D10D5D6C92E40C736C597872B7F9BD /* Tag.swift in Sources */, + 12E1368A8649F7ABCA22122BB086A9A4 /* User.swift in Sources */, + E24BD2C6E31CACD58555DB8044F7EFE4 /* UserAPI.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 14D50D2534F42D5E57F9341C234C9364 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Alamofire; - target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; - targetProxy = 53846F4D999F8096A92BE0AB60034710 /* PBXContainerItemProxy */; - }; 374AD22F26F7E9801AB27C2FCBBF4EC9 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = PetstoreClient; - target = F273DBB2E19E2286018971F2B25DEB52 /* PetstoreClient */; + target = 691AAEA1153824FE132C368C2B9D4ECF /* PetstoreClient */; targetProxy = 398B30E9B8AE28E1BDA1C6D292107659 /* PBXContainerItemProxy */; }; AC31F7EF81A7A1C4862B1BA6879CEC1C /* PBXTargetDependency */ = { @@ -753,234 +762,158 @@ target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; targetProxy = F9E1549CFEDAD61BECA92DB5B12B4019 /* PBXContainerItemProxy */; }; + F4B10CB4F7BF2C0DF6CDAFF8DA9F03B4 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; + targetProxy = FAEF364FCCB241333BC2531394A7BC5A /* PBXContainerItemProxy */; + }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ - 077C4BB7DBEAA715DED46C057DC8051C /* Release */ = { + 1928FD2BA1177E86A2DAF2641C8755AA /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */; + baseConfigurationReference = FDBB687EF1CAF131DB3DDD99AAE54AB6 /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 3.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 1FDD9BDA3D686D0B50227E3667FE27BB /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = FE7B50737921DC202987A0E4A1665B90 /* PetstoreClient.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = PetstoreClient; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; - 3F44D50290D52EC3C557274BDDAB4C7A /* Debug */ = { + 4F1AB8279A7C4737EB15C9417B058BCA /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGNING_REQUIRED = NO; COPY_PHASE_STRIP = NO; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_DEBUG=1", - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.2; - ONLY_ACTIVE_ARCH = YES; - PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Debug; - }; - 5FD3C308E1FF2B6C127426676CBBBEF9 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGNING_REQUIRED = NO; - COPY_PHASE_STRIP = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; GCC_PREPROCESSOR_DEFINITIONS = ( "POD_CONFIGURATION_RELEASE=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.2; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; STRIP_INSTALLED_PRODUCT = NO; SYMROOT = "${SRCROOT}/../build"; - VALIDATE_PRODUCT = YES; }; name = Release; }; - 86E66B7CE6321797D5D4EB3E7593B23B /* Debug */ = { + 6CD2CF3CB56F8D2390B8CD744515AD17 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; + baseConfigurationReference = 33A04B5D27E86AF4B84D95E21CF3F452 /* Alamofire.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.2; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_SwaggerClient; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_NAME = Alamofire; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Debug; + name = Release; }; - 8ABD810FE320ED013B51DFEA7CBA6A0D /* Release */ = { + 7B847FB9B14D62B0E406B600F7ECF9C5 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; + baseConfigurationReference = F388A1ADD212030D9542E86628F22BD6 /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 9.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; @@ -991,38 +924,39 @@ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; - 91CAE672CBB3E023C8A80A82BB928A22 /* Debug */ = { + 7C46BC4305EA8CA938060BF349566A75 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = FE7B50737921DC202987A0E4A1665B90 /* PetstoreClient.xcconfig */; + baseConfigurationReference = AE8315D9D127E9BAC2C7256DB40D1D6D /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = PetstoreClient; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; @@ -1031,67 +965,57 @@ }; name = Debug; }; - C66477B6E5656B1F4785FD5D9546905A /* Release */ = { + 972BD31D68F98035DE59A64D32AC1F3A /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */; + baseConfigurationReference = 33A04B5D27E86AF4B84D95E21CF3F452 /* Alamofire.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.2; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_SwaggerClientTests; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_NAME = Alamofire; SDKROOT = iphoneos; SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Release; + name = Debug; }; - D60F8C4DE6B0D221A33959774DA3DAFF /* Debug */ = { + CA2D1D2252D9383E5D37145848E5CA14 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */; + baseConfigurationReference = F1ED5AD8A7A28479CDC87C72B75010ED /* PetstoreClient.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = Alamofire; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + PRODUCT_NAME = PetstoreClient; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; @@ -1103,29 +1027,25 @@ }; name = Debug; }; - F89C2DC5B4DBA79FB9C8BA8F24E52DF4 /* Debug */ = { + E5AEBAF82849035F9A9CD1F299E57E07 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */; + baseConfigurationReference = 1ACCB3378E1513AEAADC85C4036257E4 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 9.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; @@ -1140,50 +1060,145 @@ }; name = Debug; }; + E95097900ACBDB730939D23AFE3D24CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + F821909927065327473AE031ADA63E79 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F1ED5AD8A7A28479CDC87C72B75010ED /* PetstoreClient.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 0E45B203539274106092021633F5C54E /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { isa = XCConfigurationList; buildConfigurations = ( - 91CAE672CBB3E023C8A80A82BB928A22 /* Debug */, - 1FDD9BDA3D686D0B50227E3667FE27BB /* Release */, + E95097900ACBDB730939D23AFE3D24CD /* Debug */, + 4F1AB8279A7C4737EB15C9417B058BCA /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( - 3F44D50290D52EC3C557274BDDAB4C7A /* Debug */, - 5FD3C308E1FF2B6C127426676CBBBEF9 /* Release */, + 972BD31D68F98035DE59A64D32AC1F3A /* Debug */, + 6CD2CF3CB56F8D2390B8CD744515AD17 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + 5DE561894A3D2FE43769BF10CB87D407 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { isa = XCConfigurationList; buildConfigurations = ( - D60F8C4DE6B0D221A33959774DA3DAFF /* Debug */, - 077C4BB7DBEAA715DED46C057DC8051C /* Release */, + 7C46BC4305EA8CA938060BF349566A75 /* Debug */, + 7B847FB9B14D62B0E406B600F7ECF9C5 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 5DE561894A3D2FE43769BF10CB87D407 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { + B462F7329881FF6565EF44016BE2B959 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */ = { isa = XCConfigurationList; buildConfigurations = ( - 86E66B7CE6321797D5D4EB3E7593B23B /* Debug */, - 8ABD810FE320ED013B51DFEA7CBA6A0D /* Release */, + E5AEBAF82849035F9A9CD1F299E57E07 /* Debug */, + 1928FD2BA1177E86A2DAF2641C8755AA /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - B462F7329881FF6565EF44016BE2B959 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */ = { + C82540F432F75C90F90C570A5CBBF5CA /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { isa = XCConfigurationList; buildConfigurations = ( - F89C2DC5B4DBA79FB9C8BA8F24E52DF4 /* Debug */, - C66477B6E5656B1F4785FD5D9546905A /* Release */, + CA2D1D2252D9383E5D37145848E5CA14 /* Debug */, + F821909927065327473AE031ADA63E79 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig index 619e5f4acefe..881c8cade671 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -1,9 +1,9 @@ -CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig index 904973a3bdc7..98aa9b0cc5a5 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig @@ -1,10 +1,10 @@ -CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/PetstoreClient -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PODS_TARGET_SRCROOT = ${PODS_ROOT}/../.. PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh index 4d253d901860..2eccc456916b 100755 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh @@ -6,10 +6,14 @@ mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") +# Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then @@ -58,12 +62,31 @@ install_framework() fi } -# Copies the dSYM of a vendored framework +# Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DWARF_DSYM_FOLDER_PATH}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DWARF_DSYM_FOLDER_PATH}" + # Copy the dSYM into a the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .framework.dSYM "$source")" + binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then + strip_invalid_archs "$binary" + fi + + if [[ $STRIP_BINARY_RETVAL == 1 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" + fi fi } @@ -85,10 +108,18 @@ code_sign_if_enabled() { # Strip invalid architectures strip_invalid_archs() { binary="$1" - # Get architectures for current file - archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + STRIP_BINARY_RETVAL=0 + return + fi stripped="" - for arch in $archs; do + for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 @@ -98,6 +129,7 @@ strip_invalid_archs() { if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi + STRIP_BINARY_RETVAL=1 } diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig index ad32982f5bf7..5ab6f3adf4f3 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig @@ -1,11 +1,11 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient/PetstoreClient.framework/Headers" OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PetstoreClient" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig index ad32982f5bf7..5ab6f3adf4f3 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig @@ -1,11 +1,11 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient/PetstoreClient.framework/Headers" OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PetstoreClient" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh index 88dd53799078..881cbaed3244 100755 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh @@ -6,10 +6,14 @@ mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") +# Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then @@ -58,12 +62,31 @@ install_framework() fi } -# Copies the dSYM of a vendored framework +# Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DWARF_DSYM_FOLDER_PATH}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DWARF_DSYM_FOLDER_PATH}" + # Copy the dSYM into a the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .framework.dSYM "$source")" + binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then + strip_invalid_archs "$binary" + fi + + if [[ $STRIP_BINARY_RETVAL == 1 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" + fi fi } @@ -85,10 +108,18 @@ code_sign_if_enabled() { # Strip invalid architectures strip_invalid_archs() { binary="$1" - # Get architectures for current file - archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + STRIP_BINARY_RETVAL=0 + return + fi stripped="" - for arch in $archs; do + for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 @@ -98,6 +129,7 @@ strip_invalid_archs() { if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi + STRIP_BINARY_RETVAL=1 } if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig index a3871374db07..43fd8e36c03a 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig @@ -1,8 +1,8 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient/PetstoreClient.framework/Headers" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig index a3871374db07..43fd8e36c03a 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig @@ -1,8 +1,8 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient/PetstoreClient.framework/Headers" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift index ffb9e8b209f4..f8c903f1f367 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -26,17 +26,11 @@ class PetAPITests: XCTestCase { func test1CreatePet() { let expectation = self.expectation(description: "testCreatePet") - - let newPet = Pet() - let category = PetstoreClient.Category() - category.id = 1234 - category.name = "eyeColor" - newPet.category = category - newPet.id = 1000 - newPet.name = "Fluffy" - newPet.status = .available - - PetAPI.addPet(body: newPet) { (error) in + let category = PetstoreClient.Category(_id: 1234, name: "eyeColor") + let tags = [Tag(_id: 1234, name: "New York"), Tag(_id: 124321, name: "Jose")] + let newPet = Pet(_id: 1000, category: category, name: "Fluffy", photoUrls: ["https://petstore.com/sample/photo1.jpg", "https://petstore.com/sample/photo2.jpg"], tags: tags, status: .available) + + PetAPI.addPet(body: newPet) { (response, error) in guard error == nil else { XCTFail("error creating pet") return @@ -58,7 +52,7 @@ class PetAPITests: XCTestCase { } if let pet = pet { - XCTAssert(pet.id == 1000, "invalid id") + XCTAssert(pet._id == 1000, "invalid id") XCTAssert(pet.name == "Fluffy", "invalid name") expectation.fulfill() @@ -71,7 +65,7 @@ class PetAPITests: XCTestCase { func test3DeletePet() { let expectation = self.expectation(description: "testDeletePet") - PetAPI.deletePet(petId: 1000) { (error) in + PetAPI.deletePet(petId: 1000) { (response, error) in guard error == nil else { XCTFail("error deleting pet") return diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index c387099bca52..5bc1a9756454 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -17,26 +17,19 @@ class StoreAPITests: XCTestCase { let testTimeout = 10.0 func test1PlaceOrder() { - let expectation = self.expectation(description: "testPlaceOrder") - let shipDate = Date() - - let newOrder = Order() - newOrder.id = 1000 - newOrder.petId = 1000 - newOrder.complete = false - newOrder.quantity = 10 - newOrder.shipDate = shipDate // use explicit naming to reference the enum so that we test we don't regress on enum naming - newOrder.status = Order.Status.placed - - StoreAPI.placeOrder(body: newOrder) { (order, error) in + let shipDate = Date() + let order = Order(_id: 1000, petId: 1000, quantity: 10, shipDate: shipDate, status: .placed, complete: true) + let expectation = self.expectation(description: "testPlaceOrder") + + StoreAPI.placeOrder(body: order) { (order, error) in guard error == nil else { XCTFail("error placing order: \(error.debugDescription)") return } if let order = order { - XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order._id == 1000, "invalid id") XCTAssert(order.quantity == 10, "invalid quantity") XCTAssert(order.status == .placed, "invalid status") XCTAssert(order.shipDate!.isEqual(shipDate, format: self.isoDateFormat), @@ -59,7 +52,7 @@ class StoreAPITests: XCTestCase { } if let order = order { - XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order._id == 1000, "invalid id") XCTAssert(order.quantity == 10, "invalid quantity") XCTAssert(order.status == .placed, "invalid status") @@ -73,12 +66,17 @@ class StoreAPITests: XCTestCase { func test3DeleteOrder() { let expectation = self.expectation(description: "testDeleteOrder") - StoreAPI.deleteOrder(orderId: "1000") { (error) in + StoreAPI.deleteOrder(orderId: "1000") { (response, error) in guard error == nil else { XCTFail("error deleting order") return } + guard let _ = response else { + XCTFail("response is nil") + return + } + expectation.fulfill() } diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 51b4bcab89dd..e0bc86f58c21 100644 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -42,7 +42,7 @@ class UserAPITests: XCTestCase { func testLogout() { let expectation = self.expectation(description: "testLogout") - UserAPI.logoutUser { (error) in + UserAPI.logoutUser { (response, error) in guard error == nil else { XCTFail("error logging out") return @@ -56,18 +56,9 @@ class UserAPITests: XCTestCase { func test1CreateUser() { let expectation = self.expectation(description: "testCreateUser") - - let newUser = User() - newUser.email = "test@test.com" - newUser.firstName = "Test" - newUser.lastName = "Tester" - newUser.id = 1000 - newUser.password = "test!" - newUser.phone = "867-5309" - newUser.username = "test@test.com" - newUser.userStatus = 0 - - UserAPI.createUser(body: newUser) { (error) in + let newUser = User(_id: 1000, username: "test@test.com", firstName: "Test", lastName: "Tester", email: "test@test.com", password: "test!", phone: "867-5309", userStatus: 0) + + UserAPI.createUser(body: newUser) { (response, error) in guard error == nil else { XCTFail("error creating user") return @@ -106,7 +97,7 @@ class UserAPITests: XCTestCase { func test3DeleteUser() { let expectation = self.expectation(description: "testDeleteUser") - UserAPI.deleteUser(username: "test@test.com") { (error) in + UserAPI.deleteUser(username: "test@test.com") { (response, error) in guard error == nil else { XCTFail("error deleting user") return diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIHelper.swift index b612ff90921a..81e7286d6d40 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -6,12 +6,11 @@ import Foundation -class APIHelper { - static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { - var destination = [String:Any]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = value +public struct APIHelper { + public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + let destination = source.reduce(into: [String: Any]()) { (result, item) in + if let value = item.value { + result[item.key] = value } } @@ -21,45 +20,46 @@ class APIHelper { return destination } - static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { - var destination = [String:String]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = "\(value)" + public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + return source.reduce(into: [String: String]()) { (result, item) in + if let collection = item.value as? Array { + result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = "\(value)" } } - return destination } - static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { guard let source = source else { return nil } - var destination = [String:Any]() - let theTrue = NSNumber(value: true as Bool) - let theFalse = NSNumber(value: false as Bool) - for (key, value) in source { - switch value { - case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse: - destination[key] = "\(value as! Bool)" as Any? + + return source.reduce(into: [String: Any](), { (result, item) in + switch item.value { + case let x as Bool: + result[item.key] = x.description default: - destination[key] = value + result[item.key] = item.value } - } - return destination + }) } - static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { - let returnValues = values - .filter { $0.1 != nil } - .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in - URLQueryItem(name: item._key, value:"\(item._value!)") + public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in + if let collection = item.value as? Array { + let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + result.append(URLQueryItem(name: item.key, value: value)) + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: "\(value)")) } - if returnValues.count == 0 { + } + + if destination.isEmpty { return nil } - return returnValues + return destination } - } + diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs.swift index 745d640ec1cf..2c2fc3157de4 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs.swift @@ -16,10 +16,10 @@ open class PetstoreClientAPI { open class RequestBuilder { var credential: URLCredential? var headers: [String:String] - let parameters: [String:Any]? - let isBody: Bool - let method: String - let URLString: String + public let parameters: [String:Any]? + public let isBody: Bool + public let method: String + public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift index 1d439bf00892..63377bce9981 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift @@ -19,7 +19,7 @@ open class AnotherFakeAPI { */ open class func testSpecialTags(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testSpecialTagsWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -41,8 +41,7 @@ open class AnotherFakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 660dd6b02f51..da291a94de40 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -18,7 +18,7 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerialize(body: OuterBoolean? = nil, completion: @escaping ((_ data: OuterBoolean?,_ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -37,8 +37,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -52,7 +51,7 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -75,8 +74,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -90,7 +88,7 @@ open class FakeAPI { */ open class func fakeOuterNumberSerialize(body: OuterNumber? = nil, completion: @escaping ((_ data: OuterNumber?,_ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -109,8 +107,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -124,7 +121,7 @@ open class FakeAPI { */ open class func fakeOuterStringSerialize(body: OuterString? = nil, completion: @escaping ((_ data: OuterString?,_ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -143,8 +140,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -159,7 +155,7 @@ open class FakeAPI { */ open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -181,8 +177,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -208,9 +203,13 @@ open class FakeAPI { - parameter callback: (form) None (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -262,9 +261,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -351,9 +349,13 @@ open class FakeAPI { - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -385,14 +387,13 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, "enum_query_integer": enumQueryInteger?.rawValue ]) - let nillableHeaders: [String: Any?] = [ "enum_header_string_array": enumHeaderStringArray, "enum_header_string": enumHeaderString?.rawValue @@ -410,9 +411,13 @@ open class FakeAPI { - parameter param: (body) request body - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: Any, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: Any, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -431,8 +436,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -446,9 +450,13 @@ open class FakeAPI { - parameter param2: (form) field2 - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -473,9 +481,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift index 228cee8ffbce..0e2a5670a8bb 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift @@ -19,7 +19,7 @@ open class FakeClassnameTags123API { */ open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -27,6 +27,7 @@ open class FakeClassnameTags123API { /** To test class name in snake case - PATCH /fake_classname_test + - To test class name in snake case - API Key: - type: apiKey api_key_query (QUERY) - name: api_key_query @@ -43,8 +44,7 @@ open class FakeClassnameTags123API { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 6a7425564aa7..421bbe8e9d7d 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -17,9 +17,13 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + open class func addPet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -41,8 +45,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -56,9 +59,13 @@ open class PetAPI { - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -78,12 +85,13 @@ open class PetAPI { */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey ] @@ -111,7 +119,7 @@ open class PetAPI { */ open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -216,12 +224,11 @@ open class PetAPI { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status ]) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -236,7 +243,7 @@ open class PetAPI { */ open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -341,12 +348,11 @@ open class PetAPI { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags ]) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -361,7 +367,7 @@ open class PetAPI { */ open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -432,12 +438,13 @@ open class PetAPI { */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -450,9 +457,13 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -474,8 +485,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -490,9 +500,13 @@ open class PetAPI { - parameter status: (form) Updated status of the pet (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -513,7 +527,9 @@ open class PetAPI { */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "name": name, @@ -522,9 +538,8 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -541,7 +556,7 @@ open class PetAPI { */ open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -567,7 +582,9 @@ open class PetAPI { */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { var path = "/pet/{petId}/uploadImage" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "additionalMetadata": additionalMetadata, @@ -576,9 +593,8 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 756ada76c426..571f4ef4e1e8 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -17,9 +17,13 @@ open class StoreAPI { - parameter orderId: (path) ID of the order that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -35,12 +39,13 @@ open class StoreAPI { */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -54,7 +59,7 @@ open class StoreAPI { */ open class func getInventory(completion: @escaping ((_ data: [String:Int]?,_ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -76,9 +81,8 @@ open class StoreAPI { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -93,7 +97,7 @@ open class StoreAPI { */ open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -139,12 +143,13 @@ open class StoreAPI { */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -159,7 +164,7 @@ open class StoreAPI { */ open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -208,8 +213,7 @@ open class StoreAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index cbc7bd93258e..028c5db34c34 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -17,9 +17,13 @@ open class UserAPI { - parameter body: (body) Created user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUser(body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -38,8 +42,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -52,9 +55,13 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -73,8 +80,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -87,9 +93,13 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -108,8 +118,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -122,9 +131,13 @@ open class UserAPI { - parameter username: (path) The name that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deleteUser(username: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -140,12 +153,13 @@ open class UserAPI { */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -155,12 +169,12 @@ open class UserAPI { /** Get user by user name - - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter completion: completion handler to receive the data and the error objects */ open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -208,18 +222,19 @@ open class UserAPI { "username" : "username" }}] - - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -235,7 +250,7 @@ open class UserAPI { */ open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -258,13 +273,12 @@ open class UserAPI { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username, "password": password ]) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -276,9 +290,13 @@ open class UserAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(completion: @escaping ((_ error: Error?) -> Void)) { + open class func logoutUser(completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -294,9 +312,8 @@ open class UserAPI { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -310,9 +327,13 @@ open class UserAPI { - parameter body: (body) Updated user object - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -329,12 +350,13 @@ open class UserAPI { */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 24351523736d..381fddcc81fb 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -268,7 +268,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift index 4cf4ac206af5..19ee06b1f487 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift @@ -24,4 +24,20 @@ open class JSONEncodingHelper { return params } + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { + var params: Parameters? = nil + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error) + return nil + } + } + + return params + } + } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift index 8388bfb035fc..6c1e6653b6f9 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift @@ -14,6 +14,10 @@ public struct AdditionalPropertiesClass: Codable { public var mapProperty: [String:String]? public var mapOfMapProperty: [String:[String:String]]? + public init(mapProperty: [String:String]?, mapOfMapProperty: [String:[String:String]]?) { + self.mapProperty = mapProperty + self.mapOfMapProperty = mapOfMapProperty + } public enum CodingKeys: String, CodingKey { case mapProperty = "map_property" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Animal.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Animal.swift index fa13d5e9b9f6..ba2da30fedde 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Animal.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Animal.swift @@ -14,6 +14,10 @@ public struct Animal: Codable { public var className: String public var color: String? + public init(className: String, color: String?) { + self.className = className + self.color = color + } } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift index 970b52f28e48..e04761ad1228 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift @@ -20,6 +20,11 @@ public struct ApiResponse: Codable { public var type: String? public var message: String? + public init(code: Int?, type: String?, message: String?) { + self.code = code + self.type = type + self.message = message + } } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift index 8aea70bfc69b..ac59328a279f 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift @@ -13,6 +13,9 @@ public struct ArrayOfArrayOfNumberOnly: Codable { public var arrayArrayNumber: [[Double]]? + public init(arrayArrayNumber: [[Double]]?) { + self.arrayArrayNumber = arrayArrayNumber + } public enum CodingKeys: String, CodingKey { case arrayArrayNumber = "ArrayArrayNumber" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift index c670c41c217e..1132638458fc 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift @@ -13,6 +13,9 @@ public struct ArrayOfNumberOnly: Codable { public var arrayNumber: [Double]? + public init(arrayNumber: [Double]?) { + self.arrayNumber = arrayNumber + } public enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift index 6257fb4cc9bb..14335a750539 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift @@ -15,6 +15,11 @@ public struct ArrayTest: Codable { public var arrayArrayOfInteger: [[Int64]]? public var arrayArrayOfModel: [[ReadOnlyFirst]]? + public init(arrayOfString: [String]?, arrayArrayOfInteger: [[Int64]]?, arrayArrayOfModel: [[ReadOnlyFirst]]?) { + self.arrayOfString = arrayOfString + self.arrayArrayOfInteger = arrayArrayOfInteger + self.arrayArrayOfModel = arrayArrayOfModel + } public enum CodingKeys: String, CodingKey { case arrayOfString = "array_of_string" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift index 952c337fa740..71ba400a9d7b 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -19,6 +19,14 @@ public struct Capitalization: Codable { /** Name of the pet */ public var ATT_NAME: String? + public init(smallCamel: String?, capitalCamel: String?, smallSnake: String?, capitalSnake: String?, sCAETHFlowPoints: String?, ATT_NAME: String?) { + self.smallCamel = smallCamel + self.capitalCamel = capitalCamel + self.smallSnake = smallSnake + self.capitalSnake = capitalSnake + self.sCAETHFlowPoints = sCAETHFlowPoints + self.ATT_NAME = ATT_NAME + } public enum CodingKeys: String, CodingKey { case smallCamel diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Cat.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Cat.swift index 67151f42958c..0394e377ed89 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Cat.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Cat.swift @@ -20,6 +20,11 @@ public struct Cat: Codable { } } + public init(className: String, color: String?, declawed: Bool?) { + self.className = className + self.color = color + self.declawed = declawed + } } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Category.swift index 449407291abb..a92890874d88 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Category.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -19,6 +19,10 @@ public struct Category: Codable { } public var name: String? + public init(_id: Int64?, name: String?) { + self._id = _id + self.name = name + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift index 90da5c2cf4dc..3a38128215a2 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift @@ -14,6 +14,9 @@ public struct ClassModel: Codable { public var _class: String? + public init(_class: String?) { + self._class = _class + } } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Client.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Client.swift index f4333883e631..0c4fc0d559a9 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Client.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Client.swift @@ -13,6 +13,9 @@ public struct Client: Codable { public var client: String? + public init(client: String?) { + self.client = client + } } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Dog.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Dog.swift index b86c61c0ee34..9ba84f7f8cc5 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Dog.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Dog.swift @@ -15,6 +15,11 @@ public struct Dog: Codable { public var color: String? public var breed: String? + public init(className: String, color: String?, breed: String?) { + self.className = className + self.color = color + self.breed = breed + } } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift index 145acd9dd347..084a9ab83836 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift @@ -22,6 +22,10 @@ public struct EnumArrays: Codable { public var justSymbol: JustSymbol? public var arrayEnum: [ArrayEnum]? + public init(justSymbol: JustSymbol?, arrayEnum: [ArrayEnum]?) { + self.justSymbol = justSymbol + self.arrayEnum = arrayEnum + } public enum CodingKeys: String, CodingKey { case justSymbol = "just_symbol" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index 74b693c7bb61..6374df494a32 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -16,6 +16,11 @@ public struct EnumTest: Codable { case lower = "lower" case empty = "" } + public enum EnumStringRequired: String, Codable { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } public enum EnumInteger: Int, Codable { case _1 = 1 case number1 = -1 @@ -25,13 +30,22 @@ public struct EnumTest: Codable { case number12 = -1.2 } public var enumString: EnumString? + public var enumStringRequired: EnumStringRequired public var enumInteger: EnumInteger? public var enumNumber: EnumNumber? public var outerEnum: OuterEnum? + public init(enumString: EnumString?, enumStringRequired: EnumStringRequired, enumInteger: EnumInteger?, enumNumber: EnumNumber?, outerEnum: OuterEnum?) { + self.enumString = enumString + self.enumStringRequired = enumStringRequired + self.enumInteger = enumInteger + self.enumNumber = enumNumber + self.outerEnum = outerEnum + } public enum CodingKeys: String, CodingKey { case enumString = "enum_string" + case enumStringRequired = "enum_string_required" case enumInteger = "enum_integer" case enumNumber = "enum_number" case outerEnum diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift index 720854989a3e..123546f63176 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift @@ -50,6 +50,21 @@ public struct FormatTest: Codable { public var uuid: UUID? public var password: String + public init(integer: Int?, int32: Int?, int64: Int64?, number: Double, float: Float?, double: Double?, string: String?, byte: Data, binary: Data?, date: Date, dateTime: Date?, uuid: UUID?, password: String) { + self.integer = integer + self.int32 = int32 + self.int64 = int64 + self.number = number + self.float = float + self.double = double + self.string = string + self.byte = byte + self.binary = binary + self.date = date + self.dateTime = dateTime + self.uuid = uuid + self.password = password + } } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift index 23f5e679faf3..3626846919f5 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift @@ -14,6 +14,10 @@ public struct HasOnlyReadOnly: Codable { public var bar: String? public var foo: String? + public init(bar: String?, foo: String?) { + self.bar = bar + self.foo = foo + } } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/List.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/List.swift index 382702867a89..fe11bfce8402 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/List.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/List.swift @@ -13,6 +13,9 @@ public struct List: Codable { public var _123List: String? + public init(_123List: String?) { + self._123List = _123List + } public enum CodingKeys: String, CodingKey { case _123List = "123-list" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MapTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MapTest.swift index e8f11504de5d..ded3f7b1dde1 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MapTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MapTest.swift @@ -18,6 +18,10 @@ public struct MapTest: Codable { public var mapMapOfString: [String:[String:String]]? public var mapOfEnumString: [String:String]? + public init(mapMapOfString: [String:[String:String]]?, mapOfEnumString: [String:String]?) { + self.mapMapOfString = mapMapOfString + self.mapOfEnumString = mapOfEnumString + } public enum CodingKeys: String, CodingKey { case mapMapOfString = "map_map_of_string" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 554c81317eb4..962b7fe65bc5 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -15,6 +15,11 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { public var dateTime: Date? public var map: [String:Animal]? + public init(uuid: UUID?, dateTime: Date?, map: [String:Animal]?) { + self.uuid = uuid + self.dateTime = dateTime + self.map = map + } } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift index 8bea4e98d458..c1a61cbbee7e 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift @@ -20,6 +20,10 @@ public struct Model200Response: Codable { } public var _class: String? + public init(name: Int?, _class: String?) { + self.name = name + self._class = _class + } public enum CodingKeys: String, CodingKey { case name diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Name.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Name.swift index 090d73e9206f..f013b02f16e5 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Name.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Name.swift @@ -32,6 +32,12 @@ public struct Name: Codable { } } + public init(name: Int, snakeCase: Int?, property: String?, _123Number: Int?) { + self.name = name + self.snakeCase = snakeCase + self.property = property + self._123Number = _123Number + } public enum CodingKeys: String, CodingKey { case name diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift index 78bb76f9bfd6..06db22e9c3ab 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift @@ -13,6 +13,9 @@ public struct NumberOnly: Codable { public var justNumber: Double? + public init(justNumber: Double?) { + self.justNumber = justNumber + } public enum CodingKeys: String, CodingKey { case justNumber = "JustNumber" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Order.swift index 0a5a10213291..48564f3ef60c 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -44,6 +44,14 @@ public struct Order: Codable { } } + public init(_id: Int64?, petId: Int64?, quantity: Int?, shipDate: Date?, status: Status?, complete: Bool?) { + self._id = _id + self.petId = petId + self.quantity = quantity + self.shipDate = shipDate + self.status = status + self.complete = complete + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift index 0c77ca23f503..bd1984e870db 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift @@ -15,6 +15,11 @@ public struct OuterComposite: Codable { public var myString: OuterString? public var myBoolean: OuterBoolean? + public init(myNumber: OuterNumber?, myString: OuterString?, myBoolean: OuterBoolean?) { + self.myNumber = myNumber + self.myString = myString + self.myBoolean = myBoolean + } public enum CodingKeys: String, CodingKey { case myNumber = "my_number" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Pet.swift index b0518218011b..ac59ab682921 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -29,6 +29,14 @@ public struct Pet: Codable { /** pet status in the store */ public var status: Status? + public init(_id: Int64?, category: Category?, name: String, photoUrls: [String], tags: [Tag]?, status: Status?) { + self._id = _id + self.category = category + self.name = name + self.photoUrls = photoUrls + self.tags = tags + self.status = status + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift index 7cec5cb2f927..6e984760cd6c 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift @@ -14,6 +14,10 @@ public struct ReadOnlyFirst: Codable { public var bar: String? public var baz: String? + public init(bar: String?, baz: String?) { + self.bar = bar + self.baz = baz + } } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Return.swift index d2bb266a9dd8..18dca782e1b1 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Return.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Return.swift @@ -19,6 +19,9 @@ public struct Return: Codable { } } + public init(_return: Int?) { + self._return = _return + } public enum CodingKeys: String, CodingKey { case _return = "return" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift index e5381f2b4f63..ee5a48dce695 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift @@ -18,6 +18,9 @@ public struct SpecialModelName: Codable { } } + public init(specialPropertyName: Int64?) { + self.specialPropertyName = specialPropertyName + } public enum CodingKeys: String, CodingKey { case specialPropertyName = "$special[property.name]" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Tag.swift index 4f90ec8f73d2..834e0c9a9850 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Tag.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -19,6 +19,10 @@ public struct Tag: Codable { } public var name: String? + public init(_id: Int64?, name: String?) { + self._id = _id + self.name = name + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/User.swift index 9158195c4eb0..b6b144a5b452 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/User.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -31,6 +31,16 @@ public struct User: Codable { } } + public init(_id: Int64?, username: String?, firstName: String?, lastName: String?, email: String?, password: String?, phone: String?, userStatus: Int?) { + self._id = _id + self.username = username + self.firstName = firstName + self.lastName = lastName + self.email = email + self.password = password + self.phone = phone + self.userStatus = userStatus + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift index b612ff90921a..81e7286d6d40 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -6,12 +6,11 @@ import Foundation -class APIHelper { - static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { - var destination = [String:Any]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = value +public struct APIHelper { + public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + let destination = source.reduce(into: [String: Any]()) { (result, item) in + if let value = item.value { + result[item.key] = value } } @@ -21,45 +20,46 @@ class APIHelper { return destination } - static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { - var destination = [String:String]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = "\(value)" + public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + return source.reduce(into: [String: String]()) { (result, item) in + if let collection = item.value as? Array { + result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = "\(value)" } } - return destination } - static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { guard let source = source else { return nil } - var destination = [String:Any]() - let theTrue = NSNumber(value: true as Bool) - let theFalse = NSNumber(value: false as Bool) - for (key, value) in source { - switch value { - case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse: - destination[key] = "\(value as! Bool)" as Any? + + return source.reduce(into: [String: Any](), { (result, item) in + switch item.value { + case let x as Bool: + result[item.key] = x.description default: - destination[key] = value + result[item.key] = item.value } - } - return destination + }) } - static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { - let returnValues = values - .filter { $0.1 != nil } - .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in - URLQueryItem(name: item._key, value:"\(item._value!)") + public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in + if let collection = item.value as? Array { + let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + result.append(URLQueryItem(name: item.key, value: value)) + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: "\(value)")) } - if returnValues.count == 0 { + } + + if destination.isEmpty { return nil } - return returnValues + return destination } - } + diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift index 745d640ec1cf..2c2fc3157de4 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift @@ -16,10 +16,10 @@ open class PetstoreClientAPI { open class RequestBuilder { var credential: URLCredential? var headers: [String:String] - let parameters: [String:Any]? - let isBody: Bool - let method: String - let URLString: String + public let parameters: [String:Any]? + public let isBody: Bool + public let method: String + public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift index 31b7a178c6d8..df4fef717b71 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift @@ -20,7 +20,7 @@ open class AnotherFakeAPI { */ open class func testSpecialTags(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testSpecialTagsWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -59,8 +59,7 @@ open class AnotherFakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 54124af1c3e9..5787b8818514 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -19,7 +19,7 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerialize(body: OuterBoolean? = nil, completion: @escaping ((_ data: OuterBoolean?,_ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -54,8 +54,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -69,7 +68,7 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -108,8 +107,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -123,7 +121,7 @@ open class FakeAPI { */ open class func fakeOuterNumberSerialize(body: OuterNumber? = nil, completion: @escaping ((_ data: OuterNumber?,_ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -158,8 +156,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -173,7 +170,7 @@ open class FakeAPI { */ open class func fakeOuterStringSerialize(body: OuterString? = nil, completion: @escaping ((_ data: OuterString?,_ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -208,8 +205,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -224,7 +220,7 @@ open class FakeAPI { */ open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -263,8 +259,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -290,9 +285,13 @@ open class FakeAPI { - parameter callback: (form) None (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -317,11 +316,11 @@ open class FakeAPI { */ open class func testEndpointParameters( number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> Promise { let deferred = Promise.pending() - testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { error in + testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -374,9 +373,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -463,9 +461,13 @@ open class FakeAPI { - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -484,11 +486,11 @@ open class FakeAPI { */ open class func testEnumParameters( enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil) -> Promise { let deferred = Promise.pending() - testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { error in + testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -521,14 +523,13 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, "enum_query_integer": enumQueryInteger?.rawValue ]) - let nillableHeaders: [String: Any?] = [ "enum_header_string_array": enumHeaderStringArray, "enum_header_string": enumHeaderString?.rawValue @@ -546,9 +547,13 @@ open class FakeAPI { - parameter param: (body) request body - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: Any, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: Any, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -560,11 +565,11 @@ open class FakeAPI { */ open class func testInlineAdditionalProperties( param: Any) -> Promise { let deferred = Promise.pending() - testInlineAdditionalProperties(param: param) { error in + testInlineAdditionalProperties(param: param) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -584,8 +589,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -599,9 +603,13 @@ open class FakeAPI { - parameter param2: (form) field2 - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -614,11 +622,11 @@ open class FakeAPI { */ open class func testJsonFormData( param: String, param2: String) -> Promise { let deferred = Promise.pending() - testJsonFormData(param: param, param2: param2) { error in + testJsonFormData(param: param, param2: param2) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -644,9 +652,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift index 29ecd15510ee..45952a319093 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift @@ -20,7 +20,7 @@ open class FakeClassnameTags123API { */ open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -45,6 +45,7 @@ open class FakeClassnameTags123API { /** To test class name in snake case - PATCH /fake_classname_test + - To test class name in snake case - API Key: - type: apiKey api_key_query (QUERY) - name: api_key_query @@ -61,8 +62,7 @@ open class FakeClassnameTags123API { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 2c38bce3ca0c..0aa9e65a314a 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -18,9 +18,13 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + open class func addPet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -32,11 +36,11 @@ open class PetAPI { */ open class func addPet( body: Pet) -> Promise { let deferred = Promise.pending() - addPet(body: body) { error in + addPet(body: body) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -59,8 +63,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -74,9 +77,13 @@ open class PetAPI { - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -89,11 +96,11 @@ open class PetAPI { */ open class func deletePet( petId: Int64, apiKey: String? = nil) -> Promise { let deferred = Promise.pending() - deletePet(petId: petId, apiKey: apiKey) { error in + deletePet(petId: petId, apiKey: apiKey) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -114,12 +121,13 @@ open class PetAPI { */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey ] @@ -147,7 +155,7 @@ open class PetAPI { */ open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -269,12 +277,11 @@ open class PetAPI { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status ]) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -289,7 +296,7 @@ open class PetAPI { */ open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -411,12 +418,11 @@ open class PetAPI { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags ]) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -431,7 +437,7 @@ open class PetAPI { */ open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -519,12 +525,13 @@ open class PetAPI { */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -537,9 +544,13 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -551,11 +562,11 @@ open class PetAPI { */ open class func updatePet( body: Pet) -> Promise { let deferred = Promise.pending() - updatePet(body: body) { error in + updatePet(body: body) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -578,8 +589,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -594,9 +604,13 @@ open class PetAPI { - parameter status: (form) Updated status of the pet (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -610,11 +624,11 @@ open class PetAPI { */ open class func updatePetWithForm( petId: Int64, name: String? = nil, status: String? = nil) -> Promise { let deferred = Promise.pending() - updatePetWithForm(petId: petId, name: name, status: status) { error in + updatePetWithForm(petId: petId, name: name, status: status) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -636,7 +650,9 @@ open class PetAPI { */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "name": name, @@ -645,9 +661,8 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -664,7 +679,7 @@ open class PetAPI { */ open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -709,7 +724,9 @@ open class PetAPI { */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { var path = "/pet/{petId}/uploadImage" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "additionalMetadata": additionalMetadata, @@ -718,9 +735,8 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 270ed7a5adb9..ed43f65b6a70 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -18,9 +18,13 @@ open class StoreAPI { - parameter orderId: (path) ID of the order that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -32,11 +36,11 @@ open class StoreAPI { */ open class func deleteOrder( orderId: String) -> Promise { let deferred = Promise.pending() - deleteOrder(orderId: orderId) { error in + deleteOrder(orderId: orderId) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -53,12 +57,13 @@ open class StoreAPI { */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -72,7 +77,7 @@ open class StoreAPI { */ open class func getInventory(completion: @escaping ((_ data: [String:Int]?,_ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -110,9 +115,8 @@ open class StoreAPI { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -127,7 +131,7 @@ open class StoreAPI { */ open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -190,12 +194,13 @@ open class StoreAPI { */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -210,7 +215,7 @@ open class StoreAPI { */ open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -276,8 +281,7 @@ open class StoreAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index cde1cbbffb88..b3c4f9328d6a 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -18,9 +18,13 @@ open class UserAPI { - parameter body: (body) Created user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUser(body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -32,11 +36,11 @@ open class UserAPI { */ open class func createUser( body: User) -> Promise { let deferred = Promise.pending() - createUser(body: body) { error in + createUser(body: body) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -56,8 +60,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -70,9 +73,13 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -84,11 +91,11 @@ open class UserAPI { */ open class func createUsersWithArrayInput( body: [User]) -> Promise { let deferred = Promise.pending() - createUsersWithArrayInput(body: body) { error in + createUsersWithArrayInput(body: body) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -108,8 +115,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -122,9 +128,13 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -136,11 +146,11 @@ open class UserAPI { */ open class func createUsersWithListInput( body: [User]) -> Promise { let deferred = Promise.pending() - createUsersWithListInput(body: body) { error in + createUsersWithListInput(body: body) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -160,8 +170,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -174,9 +183,13 @@ open class UserAPI { - parameter username: (path) The name that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deleteUser(username: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -188,11 +201,11 @@ open class UserAPI { */ open class func deleteUser( username: String) -> Promise { let deferred = Promise.pending() - deleteUser(username: username) { error in + deleteUser(username: username) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -209,12 +222,13 @@ open class UserAPI { */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -224,19 +238,19 @@ open class UserAPI { /** Get user by user name - - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter completion: completion handler to receive the data and the error objects */ open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } /** Get user by user name - - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - returns: Promise */ open class func getUserByName( username: String) -> Promise { @@ -294,18 +308,19 @@ open class UserAPI { "username" : "username" }}] - - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -321,7 +336,7 @@ open class UserAPI { */ open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -362,13 +377,12 @@ open class UserAPI { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username, "password": password ]) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -380,9 +394,13 @@ open class UserAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(completion: @escaping ((_ error: Error?) -> Void)) { + open class func logoutUser(completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -393,11 +411,11 @@ open class UserAPI { */ open class func logoutUser() -> Promise { let deferred = Promise.pending() - logoutUser() { error in + logoutUser() { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -414,9 +432,8 @@ open class UserAPI { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -430,9 +447,13 @@ open class UserAPI { - parameter body: (body) Updated user object - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -445,11 +466,11 @@ open class UserAPI { */ open class func updateUser( username: String, body: User) -> Promise { let deferred = Promise.pending() - updateUser(username: username, body: body) { error in + updateUser(username: username, body: body) { data, error in if let error = error { deferred.reject(error) } else { - deferred.fulfill() + deferred.fulfill(data!) } } return deferred.promise @@ -467,12 +488,13 @@ open class UserAPI { */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 24351523736d..381fddcc81fb 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -268,7 +268,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift index 4cf4ac206af5..19ee06b1f487 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift @@ -24,4 +24,20 @@ open class JSONEncodingHelper { return params } + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { + var params: Parameters? = nil + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error) + return nil + } + } + + return params + } + } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift index 8388bfb035fc..6c1e6653b6f9 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift @@ -14,6 +14,10 @@ public struct AdditionalPropertiesClass: Codable { public var mapProperty: [String:String]? public var mapOfMapProperty: [String:[String:String]]? + public init(mapProperty: [String:String]?, mapOfMapProperty: [String:[String:String]]?) { + self.mapProperty = mapProperty + self.mapOfMapProperty = mapOfMapProperty + } public enum CodingKeys: String, CodingKey { case mapProperty = "map_property" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Animal.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Animal.swift index fa13d5e9b9f6..ba2da30fedde 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Animal.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Animal.swift @@ -14,6 +14,10 @@ public struct Animal: Codable { public var className: String public var color: String? + public init(className: String, color: String?) { + self.className = className + self.color = color + } } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift index a4e416b79a85..3fd872dcd26f 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift @@ -15,6 +15,11 @@ public struct ApiResponse: Codable { public var type: String? public var message: String? + public init(code: Int?, type: String?, message: String?) { + self.code = code + self.type = type + self.message = message + } } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift index 8aea70bfc69b..ac59328a279f 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift @@ -13,6 +13,9 @@ public struct ArrayOfArrayOfNumberOnly: Codable { public var arrayArrayNumber: [[Double]]? + public init(arrayArrayNumber: [[Double]]?) { + self.arrayArrayNumber = arrayArrayNumber + } public enum CodingKeys: String, CodingKey { case arrayArrayNumber = "ArrayArrayNumber" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift index c670c41c217e..1132638458fc 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift @@ -13,6 +13,9 @@ public struct ArrayOfNumberOnly: Codable { public var arrayNumber: [Double]? + public init(arrayNumber: [Double]?) { + self.arrayNumber = arrayNumber + } public enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift index 6257fb4cc9bb..14335a750539 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift @@ -15,6 +15,11 @@ public struct ArrayTest: Codable { public var arrayArrayOfInteger: [[Int64]]? public var arrayArrayOfModel: [[ReadOnlyFirst]]? + public init(arrayOfString: [String]?, arrayArrayOfInteger: [[Int64]]?, arrayArrayOfModel: [[ReadOnlyFirst]]?) { + self.arrayOfString = arrayOfString + self.arrayArrayOfInteger = arrayArrayOfInteger + self.arrayArrayOfModel = arrayArrayOfModel + } public enum CodingKeys: String, CodingKey { case arrayOfString = "array_of_string" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift index 952c337fa740..71ba400a9d7b 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -19,6 +19,14 @@ public struct Capitalization: Codable { /** Name of the pet */ public var ATT_NAME: String? + public init(smallCamel: String?, capitalCamel: String?, smallSnake: String?, capitalSnake: String?, sCAETHFlowPoints: String?, ATT_NAME: String?) { + self.smallCamel = smallCamel + self.capitalCamel = capitalCamel + self.smallSnake = smallSnake + self.capitalSnake = capitalSnake + self.sCAETHFlowPoints = sCAETHFlowPoints + self.ATT_NAME = ATT_NAME + } public enum CodingKeys: String, CodingKey { case smallCamel diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Cat.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Cat.swift index e9e061b5e364..7687f52d477a 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Cat.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Cat.swift @@ -15,6 +15,11 @@ public struct Cat: Codable { public var color: String? public var declawed: Bool? + public init(className: String, color: String?, declawed: Bool?) { + self.className = className + self.color = color + self.declawed = declawed + } } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Category.swift index 2975a53a5079..fa0786832c63 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Category.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -14,6 +14,10 @@ public struct Category: Codable { public var _id: Int64? public var name: String? + public init(_id: Int64?, name: String?) { + self._id = _id + self.name = name + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift index 90da5c2cf4dc..3a38128215a2 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift @@ -14,6 +14,9 @@ public struct ClassModel: Codable { public var _class: String? + public init(_class: String?) { + self._class = _class + } } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Client.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Client.swift index f4333883e631..0c4fc0d559a9 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Client.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Client.swift @@ -13,6 +13,9 @@ public struct Client: Codable { public var client: String? + public init(client: String?) { + self.client = client + } } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Dog.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Dog.swift index b86c61c0ee34..9ba84f7f8cc5 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Dog.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Dog.swift @@ -15,6 +15,11 @@ public struct Dog: Codable { public var color: String? public var breed: String? + public init(className: String, color: String?, breed: String?) { + self.className = className + self.color = color + self.breed = breed + } } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift index 145acd9dd347..084a9ab83836 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift @@ -22,6 +22,10 @@ public struct EnumArrays: Codable { public var justSymbol: JustSymbol? public var arrayEnum: [ArrayEnum]? + public init(justSymbol: JustSymbol?, arrayEnum: [ArrayEnum]?) { + self.justSymbol = justSymbol + self.arrayEnum = arrayEnum + } public enum CodingKeys: String, CodingKey { case justSymbol = "just_symbol" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index 74b693c7bb61..6374df494a32 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -16,6 +16,11 @@ public struct EnumTest: Codable { case lower = "lower" case empty = "" } + public enum EnumStringRequired: String, Codable { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } public enum EnumInteger: Int, Codable { case _1 = 1 case number1 = -1 @@ -25,13 +30,22 @@ public struct EnumTest: Codable { case number12 = -1.2 } public var enumString: EnumString? + public var enumStringRequired: EnumStringRequired public var enumInteger: EnumInteger? public var enumNumber: EnumNumber? public var outerEnum: OuterEnum? + public init(enumString: EnumString?, enumStringRequired: EnumStringRequired, enumInteger: EnumInteger?, enumNumber: EnumNumber?, outerEnum: OuterEnum?) { + self.enumString = enumString + self.enumStringRequired = enumStringRequired + self.enumInteger = enumInteger + self.enumNumber = enumNumber + self.outerEnum = outerEnum + } public enum CodingKeys: String, CodingKey { case enumString = "enum_string" + case enumStringRequired = "enum_string_required" case enumInteger = "enum_integer" case enumNumber = "enum_number" case outerEnum diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift index 0ce1edc16b07..1fc4bd362fd1 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift @@ -25,6 +25,21 @@ public struct FormatTest: Codable { public var uuid: UUID? public var password: String + public init(integer: Int?, int32: Int?, int64: Int64?, number: Double, float: Float?, double: Double?, string: String?, byte: Data, binary: Data?, date: Date, dateTime: Date?, uuid: UUID?, password: String) { + self.integer = integer + self.int32 = int32 + self.int64 = int64 + self.number = number + self.float = float + self.double = double + self.string = string + self.byte = byte + self.binary = binary + self.date = date + self.dateTime = dateTime + self.uuid = uuid + self.password = password + } } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift index 23f5e679faf3..3626846919f5 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift @@ -14,6 +14,10 @@ public struct HasOnlyReadOnly: Codable { public var bar: String? public var foo: String? + public init(bar: String?, foo: String?) { + self.bar = bar + self.foo = foo + } } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/List.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/List.swift index 382702867a89..fe11bfce8402 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/List.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/List.swift @@ -13,6 +13,9 @@ public struct List: Codable { public var _123List: String? + public init(_123List: String?) { + self._123List = _123List + } public enum CodingKeys: String, CodingKey { case _123List = "123-list" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MapTest.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MapTest.swift index e8f11504de5d..ded3f7b1dde1 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MapTest.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MapTest.swift @@ -18,6 +18,10 @@ public struct MapTest: Codable { public var mapMapOfString: [String:[String:String]]? public var mapOfEnumString: [String:String]? + public init(mapMapOfString: [String:[String:String]]?, mapOfEnumString: [String:String]?) { + self.mapMapOfString = mapMapOfString + self.mapOfEnumString = mapOfEnumString + } public enum CodingKeys: String, CodingKey { case mapMapOfString = "map_map_of_string" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 554c81317eb4..962b7fe65bc5 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -15,6 +15,11 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { public var dateTime: Date? public var map: [String:Animal]? + public init(uuid: UUID?, dateTime: Date?, map: [String:Animal]?) { + self.uuid = uuid + self.dateTime = dateTime + self.map = map + } } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift index 573cb42acfd4..f539cd888ab5 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift @@ -15,6 +15,10 @@ public struct Model200Response: Codable { public var name: Int? public var _class: String? + public init(name: Int?, _class: String?) { + self.name = name + self._class = _class + } public enum CodingKeys: String, CodingKey { case name diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Name.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Name.swift index b4686c2c8a4c..ddd2b9098519 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Name.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Name.swift @@ -17,6 +17,12 @@ public struct Name: Codable { public var property: String? public var _123Number: Int? + public init(name: Int, snakeCase: Int?, property: String?, _123Number: Int?) { + self.name = name + self.snakeCase = snakeCase + self.property = property + self._123Number = _123Number + } public enum CodingKeys: String, CodingKey { case name diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift index 78bb76f9bfd6..06db22e9c3ab 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift @@ -13,6 +13,9 @@ public struct NumberOnly: Codable { public var justNumber: Double? + public init(justNumber: Double?) { + self.justNumber = justNumber + } public enum CodingKeys: String, CodingKey { case justNumber = "JustNumber" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Order.swift index 26de6d8313dc..b6c0cc0cb5a2 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -24,6 +24,14 @@ public struct Order: Codable { public var status: Status? public var complete: Bool? + public init(_id: Int64?, petId: Int64?, quantity: Int?, shipDate: Date?, status: Status?, complete: Bool?) { + self._id = _id + self.petId = petId + self.quantity = quantity + self.shipDate = shipDate + self.status = status + self.complete = complete + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift index 0c77ca23f503..bd1984e870db 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift @@ -15,6 +15,11 @@ public struct OuterComposite: Codable { public var myString: OuterString? public var myBoolean: OuterBoolean? + public init(myNumber: OuterNumber?, myString: OuterString?, myBoolean: OuterBoolean?) { + self.myNumber = myNumber + self.myString = myString + self.myBoolean = myBoolean + } public enum CodingKeys: String, CodingKey { case myNumber = "my_number" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Pet.swift index dcb32870f70a..73985167c966 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -24,6 +24,14 @@ public struct Pet: Codable { /** pet status in the store */ public var status: Status? + public init(_id: Int64?, category: Category?, name: String, photoUrls: [String], tags: [Tag]?, status: Status?) { + self._id = _id + self.category = category + self.name = name + self.photoUrls = photoUrls + self.tags = tags + self.status = status + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift index 7cec5cb2f927..6e984760cd6c 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift @@ -14,6 +14,10 @@ public struct ReadOnlyFirst: Codable { public var bar: String? public var baz: String? + public init(bar: String?, baz: String?) { + self.bar = bar + self.baz = baz + } } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Return.swift index 86c3f0d8097f..9502f08130c1 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Return.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Return.swift @@ -14,6 +14,9 @@ public struct Return: Codable { public var _return: Int? + public init(_return: Int?) { + self._return = _return + } public enum CodingKeys: String, CodingKey { case _return = "return" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift index f0c0aec53944..f94741a854a3 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift @@ -13,6 +13,9 @@ public struct SpecialModelName: Codable { public var specialPropertyName: Int64? + public init(specialPropertyName: Int64?) { + self.specialPropertyName = specialPropertyName + } public enum CodingKeys: String, CodingKey { case specialPropertyName = "$special[property.name]" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Tag.swift index 86c19a254d14..7dd17159a739 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Tag.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -14,6 +14,10 @@ public struct Tag: Codable { public var _id: Int64? public var name: String? + public init(_id: Int64?, name: String?) { + self._id = _id + self.name = name + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/User.swift index ab73f62883e5..09b68da4f8f4 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/User.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -21,6 +21,16 @@ public struct User: Codable { /** User Status */ public var userStatus: Int? + public init(_id: Int64?, username: String?, firstName: String?, lastName: String?, email: String?, password: String?, phone: String?, userStatus: Int?) { + self._id = _id + self.username = username + self.firstName = firstName + self.lastName = lastName + self.email = email + self.password = password + self.phone = phone + self.userStatus = userStatus + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Podfile.lock index fa4d4714cb96..817fb4412f2e 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Podfile.lock +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Podfile.lock @@ -1,7 +1,7 @@ PODS: - Alamofire (4.5.0) - PetstoreClient (0.0.1): - - Alamofire (~> 4.5) + - Alamofire (~> 4.5.0) - PromiseKit/CorePromise (~> 4.4.0) - PromiseKit/CorePromise (4.4.0) @@ -14,9 +14,9 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: Alamofire: f28cdffd29de33a7bfa022cbd63ae95a27fae140 - PetstoreClient: 8c88e8c9531ace21041af9c85942deac3ba99104 + PetstoreClient: 9676ada4aca5ed85343879b88b00dc0cc18d605e PromiseKit: ecf5fe92275d57ee77c9ede858af47a162e9b97e PODFILE CHECKSUM: da9f5a7ad6086f2c7abb73cf2c35cefce04a9a30 -COCOAPODS: 1.3.1 +COCOAPODS: 1.4.0 diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json index 8feb1b62368f..b96a4bed0ac2 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -2,7 +2,8 @@ "name": "PetstoreClient", "platforms": { "ios": "9.0", - "osx": "10.11" + "osx": "10.11", + "tvos": "9.0" }, "version": "0.0.1", "source": { @@ -19,7 +20,7 @@ "~> 4.4.0" ], "Alamofire": [ - "~> 4.5" + "~> 4.5.0" ] } } diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Manifest.lock index fa4d4714cb96..817fb4412f2e 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Manifest.lock +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Manifest.lock @@ -1,7 +1,7 @@ PODS: - Alamofire (4.5.0) - PetstoreClient (0.0.1): - - Alamofire (~> 4.5) + - Alamofire (~> 4.5.0) - PromiseKit/CorePromise (~> 4.4.0) - PromiseKit/CorePromise (4.4.0) @@ -14,9 +14,9 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: Alamofire: f28cdffd29de33a7bfa022cbd63ae95a27fae140 - PetstoreClient: 8c88e8c9531ace21041af9c85942deac3ba99104 + PetstoreClient: 9676ada4aca5ed85343879b88b00dc0cc18d605e PromiseKit: ecf5fe92275d57ee77c9ede858af47a162e9b97e PODFILE CHECKSUM: da9f5a7ad6086f2c7abb73cf2c35cefce04a9a30 -COCOAPODS: 1.3.1 +COCOAPODS: 1.4.0 diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj index 6d7db7a9a6ff..b8e6f46c6d24 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -7,136 +7,137 @@ objects = { /* Begin PBXBuildFile section */ - 00E45C819B259C722DA2BF90EE63DDE6 /* AdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3153AF6539569349FDEA90444438B8A /* AdditionalPropertiesClass.swift */; }; - 02650248013496C5AB857B869C562661 /* PromiseKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3C7BB9DA6D00D51D3DB475EDCFC925B3 /* PromiseKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 0B974B8BCA617D23C87619DADD37D39B /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A03102A2289886143D394C1EEF173C69 /* Alamofire.framework */; }; - 0BC6EA4CC7B942917A160339B54748B6 /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = 47F1D5162720B2001CA614017A1ACE90 /* join.m */; }; - 0E4F6AB01CA15D7ACE27641BA3803ACE /* EnumClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30E08D3E06CED1E4F2876EFA44A239ED /* EnumClass.swift */; }; + 04383899005EE36AF21F761D7DC80E95 /* DispatchQueue+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B75FBDF2B74DA3B74C5F0ADD20F42A2 /* DispatchQueue+Promise.swift */; }; + 083C731FF7E5782D19029803B9C23DE8 /* FakeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 456356DFF7271B4F562B7F04E03E3CA8 /* FakeAPI.swift */; }; + 095BBCE1E728245C9E4E162B0FE4BB6A /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AEE7AA4D6A19965503F1889B1F44B1D /* Models.swift */; }; + 0A2E76BD89D6BF6F8F889FAFEF599199 /* OuterNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC665263E59F937C09C52DBC4851F44F /* OuterNumber.swift */; }; + 0A7BAE5F9B5FF377168750D402C2D785 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 364DFA113368D39E8F9FF776C3C78B11 /* UserAPI.swift */; }; + 0AAA2459130A15FAB0A059B2C8D538A9 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = CA6251246DA0044C165AC891CDE64344 /* hang.m */; }; + 106547F65F792529AD62ADC1AC01D58F /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 80933905730AC186F9CA86852B3817E6 /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = AE6E736FF5D4320FE1647DB1724C14B8 /* Timeline.swift */; }; - 1392D80ECC22365B4831BC95032F0F0B /* Cat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4530F24A4BDA094563779F1D4313B9E1 /* Cat.swift */; }; - 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 95DA780B317CD76B87D2843B3922D627 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 1F4886332EE9958B4953893705FF9246 /* Animal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8689097AED0350F905AFA5B0962FA969 /* Animal.swift */; }; - 20E2CC1FD887EC3DA74724A32DDA1132 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 21E703668E91D10CECB8BBE59650D58F /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 854F6A83AC5201A267F39995BF249D32 /* AlamofireImplementations.swift */; }; - 2AA4FCEA014BFBBBD56C909C02B98A77 /* FakeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C6145F09A87143B7FC501BE989C8BBD /* FakeAPI.swift */; }; - 30F26AB48B6038D292000A176A0A25D2 /* ArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45CB52E75AED2F044F187FD71FDFC880 /* ArrayOfNumberOnly.swift */; }; - 3149FCFDA10385D31F93F2F781AA34D0 /* ClassModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = C925A1EF89E6AF23AE6EA4BA515A6E11 /* ClassModel.swift */; }; - 31F8B86E3672D0B828B6352C875649C4 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 32495BBAAED67B464B26E37EFC43BFAA /* OuterString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EB640315A574EA2C8E4584499B31A44 /* OuterString.swift */; }; - 34104D7277F8474FCBB80637A8364337 /* EnumTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3941FB77CA24840ADF5671D16FE460C /* EnumTest.swift */; }; - 34C9317929C1DA5F022B5AEC56DED275 /* Zalgo.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA33807992507937BA2869E4D72BA073 /* Zalgo.swift */; }; + 1103E43C29C4C4880211E7F883882F70 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC6A834DBFB72DAA5CF0C32268CDF605 /* Configuration.swift */; }; + 18E0A0C81B42135BD9A73D1670B982D7 /* OuterString.swift in Sources */ = {isa = PBXBuildFile; fileRef = D752057107F19596D3B8EA574206B2F2 /* OuterString.swift */; }; + 1A6464D1BF86829B60AA7F767B2B6228 /* wrap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04B96D6AE9F0F69FC801059349B8A234 /* wrap.swift */; }; + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = A16286911EF2D17072D77A2B43E34006 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1C0634A540F1294BEFD39E8D6EC7CDDE /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 6456A8E3DB29C967B8479EA4438C76F3 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1F1E70B6B892CFE7E8D03B3890D05C5A /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 9E9E772008F75FBB98AEE83B59F519A9 /* when.m */; }; + 20E2CC1FD887EC3DA74724A32DDA1132 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 32432BEBC9EDBC5E269C9AA0E570F464 /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 21D5CF155AB37729819479C01C692275 /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 0467D138A3101545CABA11DDD745B87B /* PetstoreClient-dummy.m */; }; + 221F18103190719148CA55FA85959C89 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 987E88064EF735B91468D5018C18E261 /* Extensions.swift */; }; + 2613421691DFA013A440D1545EE747F9 /* Fake_classname_tags123API.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49BB1DA804C4AA7D9FEF0DC43604CCCE /* Fake_classname_tags123API.swift */; }; + 27C0638829CB61F69ACAA8ADBEFB18F8 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6AFE5B442894FF7BEA9ECAB0A39B4AD /* after.swift */; }; + 28A61491F92263C04AC52DDB7D3D7C5E /* Client.swift in Sources */ = {isa = PBXBuildFile; fileRef = C26CC9E49237A04F52DC71125A1756AB /* Client.swift */; }; + 2ADC297B4E6F3FF3B8FE90461C80DC81 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F434ADE4363A510D2EFDCE14A0C5746 /* Error.swift */; }; + 2C2B0BFA01ABB26BC0961FDCEBCF9193 /* EnumTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 289EF031EA3B2CA318F7EACE05641165 /* EnumTest.swift */; }; + 2CFA4F6DB943A88101EC5E33612F3D3A /* AdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 374D32747BDC0BDD7ACFF23F5BF910C3 /* AdditionalPropertiesClass.swift */; }; + 2D1EC3F916AA171A159217B17E1DC3A5 /* Dog.swift in Sources */ = {isa = PBXBuildFile; fileRef = E28B79A691A2192E2A8595ACB60CC54C /* Dog.swift */; }; + 30A481BDA67CB3CF0C136A908EC50D64 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A03102A2289886143D394C1EEF173C69 /* Alamofire.framework */; }; + 31582924647B36C90C9B7763F14905F8 /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 791E26F1F38D683DDDDF5B5A4B3D6607 /* MixedPropertiesAndAdditionalPropertiesClass.swift */; }; + 31F8B86E3672D0B828B6352C875649C4 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = CF1ECC5499BE9BF36F0AE0CE47ABB673 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F8D293ABA4E6DE8B257C7E9899F1B08 /* TaskDelegate.swift */; }; - 36C43C6EB14FFC6C23618D2EE8C6D64B /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 897799EBBCCE802354256F9E7984C2CF /* StoreAPI.swift */; }; - 38C508C4B73F4EEF12972C4DEBBB59BD /* ApiResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3102957D0FBF5FFA80969BB2A15F8FF /* ApiResponse.swift */; }; - 3A6675715B2BD21963134EE7CB699FEE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B9A5CB4B436C4A88BA49990C94DB065 /* Foundation.framework */; }; - 453006CD439DABF8B2B378F4A40AC1CA /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 411BB07BE03DCC7000891F6A5E62BBC6 /* Configuration.swift */; }; - 46C3E70BD716E72351EA9828A496E59A /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = CA6251246DA0044C165AC891CDE64344 /* hang.m */; }; - 4CEC13EBEA756DB01D9EDD495477148E /* OuterNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BA93068A5B18A779CC9B0FC3F685400 /* OuterNumber.swift */; }; - 4D46B19B21C17385C251DBFD6B5CC9B5 /* JSONEncodingHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB3DDF6C3277994828CD09F3155BB74E /* JSONEncodingHelper.swift */; }; - 4E875FE97DC4CFCD45EF180B1930BA87 /* ArrayOfArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B900B675208453FB7767B0D97D50932 /* ArrayOfArrayOfNumberOnly.swift */; }; - 50FC50E41FA283FD8EACEED8EB7CC15C /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4B3F69D54C19FC502362EEE3544ECA0 /* User.swift */; }; + 36F8AE4A7F55750F441C4EA540D1699C /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = 3EDF4D8C4A3CD3A61ACE20A71F71A107 /* after.m */; }; + 3CFA2361C8B43583460324BE5C3F0AA2 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 712969C66751DDCC0D484F06819ADFAF /* PetAPI.swift */; }; + 3D7779C784C66A0C30436BD2CA2C0F40 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = B988BD8876FEE563F8D7A6E2534BA48B /* Tag.swift */; }; + 405B9F95A650E2FEC0ED1BCAE7682AA7 /* SpecialModelName.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F72B7A542B1D04D38B262F407D0F92F /* SpecialModelName.swift */; }; + 4818A1E024F6FAE56EFCC63F1C0F9631 /* Model200Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF3A2EA92DAC72BC0CED7B12F16198BD /* Model200Response.swift */; }; + 496F991DDEDAE92703CAA24CE165B9F3 /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DD27DB5AB64425B97113FA8D5A10F19 /* PromiseKit.framework */; }; + 4D2ECA6C094192F32B0B6F65481D7E47 /* Promise+AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 947066689D96D035F88E7408FA47E193 /* Promise+AnyPromise.swift */; }; + 50535053DF0B148D8D55C84AACE3E821 /* ArrayTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 584CE59DFDF2D30A308478C17A426ADA /* ArrayTest.swift */; }; + 52D5D882F7A76CCC2E82CEC51E4C4A8F /* Capitalization.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD18CDAD22507BB2C69589FD60138F66 /* Capitalization.swift */; }; 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8A3F20B5239DF2DF6CB987D4827C198 /* Request.swift */; }; - 5491C5AA65355E89637F78928E52D24C /* Client.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B8F990A8905B95231C6D1955750D23C /* Client.swift */; }; - 5742106D27D324737B72F32CBAC98924 /* HasOnlyReadOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5DF7C9C577375BE47CAE380DE3EBE19 /* HasOnlyReadOnly.swift */; }; - 58F07EB0BF05A369A3952852632562F6 /* EnumArrays.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88EC57640E276EA2387256530FB1F868 /* EnumArrays.swift */; }; + 54A8DFD3F23A65EBEBEE381B8B18107A /* PromiseKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = E63746E0EEDB9AB11F3F623A63F36BB3 /* PromiseKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 55692168300BC109D310F93B530B4132 /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9CE45709BBC984B7998B833B10FC058 /* AnyPromise.swift */; }; 5F4F4E0D84288987C470DFAE80E9C7AB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B9A5CB4B436C4A88BA49990C94DB065 /* Foundation.framework */; }; - 60E0243A7018DE1E7755825685D30151 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02E62B78D97471D708B23605FCAA9EA1 /* Tag.swift */; }; 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F48DFEE4376C36D6CF4C7DBFEBF91F45 /* DispatchQueue+Alamofire.swift */; }; 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 428236967C1B816363FB039AD9A0D098 /* ServerTrustPolicy.swift */; }; - 669789618901F2B104F686A8A44E4F23 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F434ADE4363A510D2EFDCE14A0C5746 /* Error.swift */; }; - 6939CF29A58F770558A46D229F33CDEF /* join.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54DD29EE59FE04DF98E96700B3A276DB /* join.swift */; }; - 6FABE818191D2C7497B657CB717435A9 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3ED6F43B3A7602CD88ED67B9873B2036 /* Models.swift */; }; + 631846166C39D7961C0FC2420A814D5D /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CAF4F2E2C16A07E038AAA59349BBCD9 /* AlamofireImplementations.swift */; }; + 64FBE4A1A786C4AFE12ADD42ECD1572A /* OuterBoolean.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD15E529B026F88FF8EAE32BD84D468D /* OuterBoolean.swift */; }; + 65FFD0F2A18B865A83654491E2822133 /* Return.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB0F6DF945AB4286D73C45A2139ED7B3 /* Return.swift */; }; + 667D55108CF6FE31F77C42480691A11F /* ReadOnlyFirst.swift in Sources */ = {isa = PBXBuildFile; fileRef = 896B006368E7DC47A51391033A97C2EE /* ReadOnlyFirst.swift */; }; + 6997A0FD680C0A48DEF678CED18DA37B /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05D32F7DA10CFDD71EAA3EA19946CD1D /* when.swift */; }; + 70BFDB7E47A8CCB22B535EDCBDAABC7C /* State.swift in Sources */ = {isa = PBXBuildFile; fileRef = E775A7621846699F1A762DB966B3DC48 /* State.swift */; }; 73B9C996AED49ED7CF8EC2A6F1738059 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B9A5CB4B436C4A88BA49990C94DB065 /* Foundation.framework */; }; + 75E75F96CB55F0D28EE06BAB415C26DC /* AnotherfakeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51830C53E0E76A54309CE2137E716625 /* AnotherfakeAPI.swift */; }; + 777BF05C3DD2E08DB3E3EED5F97A0CD8 /* JSONEncodableEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5EB60B9D147E1DCD36D55283254A515 /* JSONEncodableEncoding.swift */; }; + 7AE27271C19BB4061041C31FCA3244D2 /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C78CDA7E4BB301D917FE7CFBD2457EF /* APIHelper.swift */; }; 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64759A200040719DDE024A0F1BCDDDEE /* SessionDelegate.swift */; }; + 7BFA5408D6C0495B19C0CDDEA71474D5 /* Name.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E3B882B966B7AF813A56A7DA9DA1F1C /* Name.swift */; }; 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE689938DB1BB3BAF7C98928CB02978A /* Result.swift */; }; - 7DBDDA5406CB59867FC877F1032BC905 /* Return.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87DCB85380B2EC22CFE743BEDE7E4114 /* Return.swift */; }; - 7F7153A9E140DB803EFB19D4C3D2408A /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3581DEB2B2BDC3D8A0BF7C43BD317506 /* APIs.swift */; }; - 812B1864BB988DE4C71DE5755B9A7D1C /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24D3039E712D1279434152E805AEDA65 /* Order.swift */; }; - 85543B6F540EED8FFF82015FED6CB68B /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9CE45709BBC984B7998B833B10FC058 /* AnyPromise.swift */; }; - 8591B80B88C9A955D3E898EEF9DA71E1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B9A5CB4B436C4A88BA49990C94DB065 /* Foundation.framework */; }; - 8628572254ED43AD0FB157E20D3B6DCF /* Name.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C0EF68B5117187E979D1DE4ECDB938E /* Name.swift */; }; - 8740BC8B595A54E9C973D7110740D43F /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; - 878E6E228B4A3D2725656142AA379D7F /* Promise+Properties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24AEF2E680D3A5F36B2C7C53FA70938A /* Promise+Properties.swift */; }; - 884B23FB0C4EA228B4694F191D531090 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = F05D3E8C18F8C0EF732558438FAA421A /* Extensions.swift */; }; - 888EF901304106608916A05E6EC6A0A0 /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = E7B845A9435BD8A5A34664D1A66B8484 /* PromiseKit-dummy.m */; }; - 897985FA042CD12B825C3032898FAB26 /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; - 95DD56D8244A0F779EA3D24617389DFA /* GlobalState.m in Sources */ = {isa = PBXBuildFile; fileRef = 7824BE1937712800889974B222CAB1AD /* GlobalState.m */; }; - 9621FE3846B399A31C9D874A68B814EA /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FB1FE2028948C532392F549A4356FBC /* MixedPropertiesAndAdditionalPropertiesClass.swift */; }; - 98859B984F0B8D1BA8C419626A541DDF /* State.swift in Sources */ = {isa = PBXBuildFile; fileRef = E775A7621846699F1A762DB966B3DC48 /* State.swift */; }; - 989A8D9C15575595501B0525EA04B7C4 /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DD27DB5AB64425B97113FA8D5A10F19 /* PromiseKit.framework */; }; - 9DCADBA52F4BA9C2BCDD2AD9FC39291E /* DispatchQueue+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B75FBDF2B74DA3B74C5F0ADD20F42A2 /* DispatchQueue+Promise.swift */; }; + 7FCA54A30C9BD117FC96CC045BBB58BE /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22932972F4F492160D4694C01CAF311D /* Promise.swift */; }; + 802E48AE09C6A80FD22638D72C73A747 /* JSONEncodingHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = F46B1129B323D17632F7089F71632F60 /* JSONEncodingHelper.swift */; }; + 80BF18A2B7CCB1144BDF94B1B9C94F4C /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = ACDBB9A0818694ED3F5545A2102E7624 /* dispatch_promise.m */; }; + 8117E1FE605C93F0136EF1FA853AE6DD /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = 47F1D5162720B2001CA614017A1ACE90 /* join.m */; }; + 84BA25DC929E84CEEA3A86A6A6168175 /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2293B3E9936106C01A2A831A2C1E8AD6 /* race.swift */; }; + 8740BC8B595A54E9C973D7110740D43F /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FCC3BC0A0823C3FF68C4E1EF67B2FD /* Pods-SwaggerClient-dummy.m */; }; + 897985FA042CD12B825C3032898FAB26 /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 721957E37E3EE5DB5F8DBF20A032B42A /* Pods-SwaggerClientTests-dummy.m */; }; + 9394F85AA6ED6214DE27966C68945180 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 55CCB86279C9704891B8B855CA6380F6 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 98E6C302C43D21D3C7E655C6AB628229 /* CodableHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06D5E6CDDEE294F817C22C521B562508 /* CodableHelper.swift */; }; 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA7D6AB49001069ED310CBCA8FCBB44 /* AFError.swift */; }; A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AE857E00E364AD3F18C2C39D49D6DDD /* NetworkReachabilityManager.swift */; }; - A3B4F53480EF96400D782F3507A42573 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6AFE5B442894FF7BEA9ECAB0A39B4AD /* after.swift */; }; - A6FAEDD331C7E9BD959076F2CC466B5A /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = CB66B121BF9B4DF48FE2F6A4D044C443 /* AnyPromise.m */; }; - A7803F0032BE57E83C9E1CC15442058E /* SpecialModelName.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7E7932024A79370E61700F5FD439D37 /* SpecialModelName.swift */; }; - A9A1683640F2AEEE1463B4564735F52C /* MapTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF26681AB7FB981F237CD8EA4F059708 /* MapTest.swift */; }; - A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 4AC04C8B5F4B690622341DB807DAEB0B /* Alamofire-dummy.m */; }; - AA022DF933E15BC6AF9A8C157370CF96 /* Dog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28F73294B64CD8821EC2467CB7F1F073 /* Dog.swift */; }; + A4CF090C8C8CAB1F0DA8DB338C80F144 /* OuterEnum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E5EF70E686134181F06537A75BA0FD2 /* OuterEnum.swift */; }; + A56117A0D1F9C17CDAEC93D025808F95 /* ClassModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 828ED4B097AAB98D5568D37B8AECAFD0 /* ClassModel.swift */; }; + A564637BF264BB4CFB6FEF9CB75104A1 /* Animal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 171602313BBD5AE0D5F50FFB70A96CED /* Animal.swift */; }; + A86F3B3FE87D83AF99AB9BFC8155628B /* NumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3036A4C6739CD7F9D802133405FB095 /* NumberOnly.swift */; }; + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 60347AB0041CEAF3AFE665EDD5ED3839 /* Alamofire-dummy.m */; }; + ACB6244F92A66923FBDE06DB52FC0E58 /* FakeClassnameTags123API.swift in Sources */ = {isa = PBXBuildFile; fileRef = A145777600D2D0E2B9427EEE317DF443 /* FakeClassnameTags123API.swift */; }; AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9585493102C1567226760B6BACFDF648 /* SessionManager.swift */; }; - AF0CAB7D38117E91D76835CE62FE9530 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1FF93AC280A80800873A20A8F72AD29 /* Pet.swift */; }; - B319CCF9C8F0F08FADAEA89F9655B54E /* wrap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04B96D6AE9F0F69FC801059349B8A234 /* wrap.swift */; }; - B40BA9338A0622CC69161949F42E0ADE /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = 3EDF4D8C4A3CD3A61ACE20A71F71A107 /* after.m */; }; - B65BFA719D8195A2FAA0E067DE5A6DA4 /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 6456A8E3DB29C967B8479EA4438C76F3 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B0556940CFFF7904CA9C2CAB1AF71FB3 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32EFBC701E63AE331BC0BF170B2C1E2B /* User.swift */; }; + B084B1F97F44DD44E97DE9609E63339C /* FormatTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4F28D074D15DD5B49DC39B3706C7C87 /* FormatTest.swift */; }; + B207CF0DA3B3545959B5B95FBBB53D9B /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 4667C7609366DAC2FC770F6565F7F2A2 /* PromiseKit-dummy.m */; }; + B5AB1B6A32A9C6089D4C6B45C0F62908 /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 697B1649F70C9355E6ED995300DBBA28 /* APIs.swift */; }; B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = D75CBCB14282D5EBA5A424CCF0655C2A /* MultipartFormData.swift */; }; - B6FE8649C8F2D879752D6CC0BAA7D8D3 /* JSONEncodableEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 466D426E7AA31C27ABC601DD606EF126 /* JSONEncodableEncoding.swift */; }; - BA9D88BD67EA9ACBDE9FEBF06E4FBD4D /* CodableHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7EA034E64EC60C1FCC5609CA9962CD51 /* CodableHelper.swift */; }; - BB3C554F09627EA5E6E36084E4AA5545 /* fwd.h in Headers */ = {isa = PBXBuildFile; fileRef = 645D2C8A204D8C820EEF9684DC5A65F8 /* fwd.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BAA40BFDD985C530D27C930B3C68B1B1 /* List.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEE2B177461F2E7FC327D113FEC55D4 /* List.swift */; }; BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A7F97EB8AC32E44E21839FA607D2CE /* Validation.swift */; }; - BE111800D151B74E9EB6CFFA5375A378 /* Promise+AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 947066689D96D035F88E7408FA47E193 /* Promise+AnyPromise.swift */; }; + BD32F9E3B06BF67B0247C821095F7247 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EF8BA4CB172F8F6925C18B674169419 /* Pet.swift */; }; BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D5BF61C764F8D1E7F2631DE14AC6B36 /* ParameterEncoding.swift */; }; - C2C77FE3B30FA828B5A6F8611C84AB03 /* NumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A332587F10679E262455F979B3D1055 /* NumberOnly.swift */; }; - C36D10DCACB58234D9ADAE75457BB1F7 /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2293B3E9936106C01A2A831A2C1E8AD6 /* race.swift */; }; - C57A01A8A02024DD3C4F013AB8F41F71 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 475EFFB863F38801DE73965C1438E2FF /* PetAPI.swift */; }; - C77EFC1A12788F4EC02C8F08DF687A1B /* ArrayTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30B827D77F92D24E6D24561F491F2A50 /* ArrayTest.swift */; }; - C807A7AC785D77909FF2288E66669889 /* OuterComposite.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AE839994FB9B18B77FC95BCC9594683 /* OuterComposite.swift */; }; - C9004CA15837C724215DE3E1A7AB42AB /* Capitalization.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0A482A15F21B4BC206B31E7A0FAB79F /* Capitalization.swift */; }; - CAA786E247A67408ED8FDDD3BD9EACC3 /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 9E9E772008F75FBB98AEE83B59F519A9 /* when.m */; }; + BECEC463EA228A617DDC97A74DC82317 /* EnumClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF4FEED941249256FD7E23C19D4567AC /* EnumClass.swift */; }; + BEEF2C5F2E966C2177FE98B2D72CF0BF /* AnimalFarm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F80C8976AE5FBE0927AD59150439B97 /* AnimalFarm.swift */; }; + BEFC359220E7DA4FA032F4B3B1235AA7 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B9A5CB4B436C4A88BA49990C94DB065 /* Foundation.framework */; }; + C148EBC0FC3237381FFE4C0848DCAD0B /* join.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54DD29EE59FE04DF98E96700B3A276DB /* join.swift */; }; CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 714D784CFA6CB99C3B07B03487960BE0 /* Response.swift */; }; - D54935D8A773E7BC8DED0861487D5CEB /* OuterBoolean.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21A143975CF52EBFEF79A307CC7CB00E /* OuterBoolean.swift */; }; - D54B91CA1FC091E900319969 /* FakeClassnameTags123API.swift in Sources */ = {isa = PBXBuildFile; fileRef = D54B91C81FC091E900319969 /* FakeClassnameTags123API.swift */; }; - D54B91CB1FC091E900319969 /* AnotherfakeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = D54B91C91FC091E900319969 /* AnotherfakeAPI.swift */; }; - D6184AB54A12F4F580FE7766FFD1A491 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22932972F4F492160D4694C01CAF311D /* Promise.swift */; }; - D9FEE02D3C00097A882DCF9AF60C4FDC /* FormatTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9776B33259DFB803A3E6D9573FA3DE3E /* FormatTest.swift */; }; - DBFDFCF61E2F2C7A49FD50B9222E3495 /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7417953898146193F86A165CD5F3AF4A /* Category.swift */; }; - DDF666793202988950DA52A8C528C076 /* Model200Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3617A5AF85A2814F852C73FD5D575262 /* Model200Response.swift */; }; - E52BCAD4A070EEAA1EA08F2D299F4EDB /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 158D0513D0844E7FE6AEFAEE70E88618 /* UserAPI.swift */; }; + CE1E54F275C78733C1920B8843E0FE7F /* EnumArrays.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30C1E56142D8B120BDDE2AF5CA160E22 /* EnumArrays.swift */; }; + CF6B474D37B11F62B01420187A4BC8E8 /* Cat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36EB25B2EACD40B282A658DA456B0FED /* Cat.swift */; }; + D61DF6FE79C6EB404622E9BB8BA73D0E /* ApiResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 670103307A767288F991B17974F3E258 /* ApiResponse.swift */; }; + D725087C0D7C1C9A7A55AB21895AC621 /* Promise+Properties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24AEF2E680D3A5F36B2C7C53FA70938A /* Promise+Properties.swift */; }; + D88DA7B51E85EFDE66A1E2FB8E15A961 /* ArrayOfArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = A08C7F48AC7ABF4E88804808C4EB68F1 /* ArrayOfArrayOfNumberOnly.swift */; }; + DBD92C6CA90C0BD1C4C06C2BE18919DA /* OuterComposite.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9F529192DED719D7A55A3E804866F26 /* OuterComposite.swift */; }; + DCA4F98E74966A61AB0694E91D2059E8 /* HasOnlyReadOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFD9B6C73F406E259D12AAD66EB86E3A /* HasOnlyReadOnly.swift */; }; + E0D2E9BDF0D339F6DB14A81CF4BDB0CE /* ArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = B99164AE8FDE28FAD698B280AC716F77 /* ArrayOfNumberOnly.swift */; }; E723EED99F633C8620915572700A2D2E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B9A5CB4B436C4A88BA49990C94DB065 /* Foundation.framework */; }; - E80880F475CC14AFB6795F1451DDE2B4 /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9930F8E68307FDF3470DAFB398895B2 /* APIHelper.swift */; }; - E86EED1FA38087909568DED335E7B9A5 /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 3B26D25AFB2018A320BA1C7EDE3F560C /* PetstoreClient-dummy.m */; }; - E8AD4D7E49710B99BFD77E32C5EBFAE8 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = C0C60220F2C965335A15C6C5688ACE4F /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - E9783E1D3A6A0CD9CF2ACCA74A89CC8F /* AnimalFarm.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3862A83F9BE857B1E903ABBBDE37EF7 /* AnimalFarm.swift */; }; - EF15BEAF1A002B97A226F9AF3D3C0F26 /* ReadOnlyFirst.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A0977DBA9BAE46013DFD65E4400A0CB /* ReadOnlyFirst.swift */; }; + E8381C638D5A359B3253A52097E8B36A /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = CB66B121BF9B4DF48FE2F6A4D044C443 /* AnyPromise.m */; }; EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC1CEE597A54C622C960B36A5EC2FA0F /* Notifications.swift */; }; + F149C816B083DD631AECBCADE6D525A7 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B9A5CB4B436C4A88BA49990C94DB065 /* Foundation.framework */; }; + F200D84ABF9E46CE68D20FA0107CB998 /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84B5DCFB56EC99326DEBD055A032458E /* Category.swift */; }; + F3365947E0B9BD60F15F14C0C2F644E8 /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98A8E010F6244706560DDC29B122EBAF /* StoreAPI.swift */; }; F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 948BFEDB052F09AD8DAE3BD3CB286673 /* ResponseSerialization.swift */; }; + F80BFCE54D77C81CA17F4CEEBEBE394D /* MapTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38F502D93EB2D1D9C2A1283F96BFF4D2 /* MapTest.swift */; }; F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23C4E6603FB90F49BE8906508887D859 /* Alamofire.swift */; }; - F9D35B36A805D504C9383C5743874D23 /* OuterEnum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13C6EEF1D81A0C523AE569F1732AC8DC /* OuterEnum.swift */; }; - FC0B3667BB40C86FC84990EEDF29B534 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = ACDBB9A0818694ED3F5545A2102E7624 /* dispatch_promise.m */; }; - FCB75043BDF47C08F944EFD06D4636D9 /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05D32F7DA10CFDD71EAA3EA19946CD1D /* when.swift */; }; - FD5C92BE0C43E605D5AED2BEE74BC595 /* List.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B87E0BA794A79025212F37D32449C63 /* List.swift */; }; - FE73D6A3B0670590535EC0D79F4F7246 /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 80933905730AC186F9CA86852B3817E6 /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F97FBC27216FCA32291E371DC468FCFA /* GlobalState.m in Sources */ = {isa = PBXBuildFile; fileRef = 7824BE1937712800889974B222CAB1AD /* GlobalState.m */; }; + FC35F21E2F24A684684707DAA3745F36 /* fwd.h in Headers */ = {isa = PBXBuildFile; fileRef = 645D2C8A204D8C820EEF9684DC5A65F8 /* fwd.h */; settings = {ATTRIBUTES = (Public, ); }; }; + FC84AAA8BB9ED0767994FAA4FC65EE71 /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EB94F5F2FE938ECEA46481E25FFA28F /* Order.swift */; }; + FCB76B4B93511BE442511A358CDA4779 /* Zalgo.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA33807992507937BA2869E4D72BA073 /* Zalgo.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 0166D6CEA46A405AF6440470518778BB /* PBXContainerItemProxy */ = { + 4F56515656F716821CBADACB7A9CB467 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; remoteInfo = Alamofire; }; - 2A6F85761AF8DEABF6BBF52FD80B83C1 /* PBXContainerItemProxy */ = { + 8CC739769B7ED206269C0591EE53BD65 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 05AABECB91CEE9C8C520680DDD9BA9AB; + remoteGlobalIDString = 0E4534BC972F48AE7712EBE0EBE4A62A; remoteInfo = PromiseKit; }; B173CFF2A1174933D7851E8CE1CA77AB /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = BEF02C72A6656158D171985B49ABDD62; + remoteGlobalIDString = A9570E2CBF2CCB6FF2D1D0BCBC2C1DA4; remoteInfo = PetstoreClient; }; BBE116AAF20C2D98E0CC5B0D86765D22 /* PBXContainerItemProxy */ = { @@ -150,163 +151,155 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 05AABECB91CEE9C8C520680DDD9BA9AB; + remoteGlobalIDString = 0E4534BC972F48AE7712EBE0EBE4A62A; remoteInfo = PromiseKit; }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; - 02E62B78D97471D708B23605FCAA9EA1 /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; - 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; + 0467D138A3101545CABA11DDD745B87B /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; 04B96D6AE9F0F69FC801059349B8A234 /* wrap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = wrap.swift; path = Sources/wrap.swift; sourceTree = ""; }; 05D32F7DA10CFDD71EAA3EA19946CD1D /* when.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = when.swift; path = Sources/when.swift; sourceTree = ""; }; + 06D5E6CDDEE294F817C22C521B562508 /* CodableHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CodableHelper.swift; path = PetstoreClient/Classes/Swaggers/CodableHelper.swift; sourceTree = ""; }; 08A7F97EB8AC32E44E21839FA607D2CE /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; - 0B4A4A4EB2DBD6F56B1383E53763FD1B /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 08BDFE9C9E9365771FF2D47928E3E79A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; + 0AD61F8554C909A3AFA66AD9ECCB5F23 /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; + 0B4A4A4EB2DBD6F56B1383E53763FD1B /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = PetstoreClient.framework; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 0B75FBDF2B74DA3B74C5F0ADD20F42A2 /* DispatchQueue+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Promise.swift"; path = "Sources/DispatchQueue+Promise.swift"; sourceTree = ""; }; - 0BA93068A5B18A779CC9B0FC3F685400 /* OuterNumber.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterNumber.swift; sourceTree = ""; }; - 13C6EEF1D81A0C523AE569F1732AC8DC /* OuterEnum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterEnum.swift; sourceTree = ""; }; - 158D0513D0844E7FE6AEFAEE70E88618 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; - 17FF216D0378037475BAB48A20D5CB0F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 1B900B675208453FB7767B0D97D50932 /* ArrayOfArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfArrayOfNumberOnly.swift; sourceTree = ""; }; - 1F11D15E4489C7F4DC1171EB9F5448D0 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; - 21A143975CF52EBFEF79A307CC7CB00E /* OuterBoolean.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterBoolean.swift; sourceTree = ""; }; + 171602313BBD5AE0D5F50FFB70A96CED /* Animal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Animal.swift; sourceTree = ""; }; + 19CFD6BC7040A5BC22831D4B5EB7F793 /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = PetstoreClient.modulemap; sourceTree = ""; }; + 1ACCB3378E1513AEAADC85C4036257E4 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; + 1E9A49B1D85B7A38F2CAD05F245B27C3 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 22932972F4F492160D4694C01CAF311D /* Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Promise.swift; path = Sources/Promise.swift; sourceTree = ""; }; 2293B3E9936106C01A2A831A2C1E8AD6 /* race.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; 23C4E6603FB90F49BE8906508887D859 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; 24AEF2E680D3A5F36B2C7C53FA70938A /* Promise+Properties.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Properties.swift"; path = "Sources/Promise+Properties.swift"; sourceTree = ""; }; - 24D3039E712D1279434152E805AEDA65 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; - 28F73294B64CD8821EC2467CB7F1F073 /* Dog.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Dog.swift; sourceTree = ""; }; - 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; - 2A332587F10679E262455F979B3D1055 /* NumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NumberOnly.swift; sourceTree = ""; }; - 2ACC287E45C0FCE8717A34B8ECA88A30 /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = ""; }; - 2C0EF68B5117187E979D1DE4ECDB938E /* Name.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Name.swift; sourceTree = ""; }; - 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; - 30B827D77F92D24E6D24561F491F2A50 /* ArrayTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayTest.swift; sourceTree = ""; }; - 30E08D3E06CED1E4F2876EFA44A239ED /* EnumClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumClass.swift; sourceTree = ""; }; - 34E180DB9A06BFDDA525853716B57541 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 3581DEB2B2BDC3D8A0BF7C43BD317506 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIs.swift; path = PetstoreClient/Classes/Swaggers/APIs.swift; sourceTree = ""; }; - 3617A5AF85A2814F852C73FD5D575262 /* Model200Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Model200Response.swift; sourceTree = ""; }; - 3B26D25AFB2018A320BA1C7EDE3F560C /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; - 3C7BB9DA6D00D51D3DB475EDCFC925B3 /* PromiseKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-umbrella.h"; sourceTree = ""; }; + 27E9F1130735B56DF22A1439B5BA6333 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 289EF031EA3B2CA318F7EACE05641165 /* EnumTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumTest.swift; sourceTree = ""; }; + 2A8ED560E3DF01E75E0272F7A1B911DD /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + 2AEE7AA4D6A19965503F1889B1F44B1D /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Models.swift; path = PetstoreClient/Classes/Swaggers/Models.swift; sourceTree = ""; }; + 30C1E56142D8B120BDDE2AF5CA160E22 /* EnumArrays.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumArrays.swift; sourceTree = ""; }; + 32432BEBC9EDBC5E269C9AA0E570F464 /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; + 32EFBC701E63AE331BC0BF170B2C1E2B /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; + 364DFA113368D39E8F9FF776C3C78B11 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; + 36EB25B2EACD40B282A658DA456B0FED /* Cat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Cat.swift; sourceTree = ""; }; + 374D32747BDC0BDD7ACFF23F5BF910C3 /* AdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AdditionalPropertiesClass.swift; sourceTree = ""; }; + 38F502D93EB2D1D9C2A1283F96BFF4D2 /* MapTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MapTest.swift; sourceTree = ""; }; 3D5BF61C764F8D1E7F2631DE14AC6B36 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; - 3ED6F43B3A7602CD88ED67B9873B2036 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Models.swift; path = PetstoreClient/Classes/Swaggers/Models.swift; sourceTree = ""; }; + 3E5EF70E686134181F06537A75BA0FD2 /* OuterEnum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterEnum.swift; sourceTree = ""; }; 3EDF4D8C4A3CD3A61ACE20A71F71A107 /* after.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; - 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; - 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 3FB1FE2028948C532392F549A4356FBC /* MixedPropertiesAndAdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MixedPropertiesAndAdditionalPropertiesClass.swift; sourceTree = ""; }; - 411BB07BE03DCC7000891F6A5E62BBC6 /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = PetstoreClient/Classes/Swaggers/Configuration.swift; sourceTree = ""; }; - 425268D5A6D1CD870A663BBE38B62B46 /* PromiseKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.xcconfig; sourceTree = ""; }; + 408CD558DEC1EFB9C57002ADB50665FC /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 419496CDDD7E7536CBEA02BAEE2C7C21 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 428236967C1B816363FB039AD9A0D098 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; - 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; - 4530F24A4BDA094563779F1D4313B9E1 /* Cat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Cat.swift; sourceTree = ""; }; - 45CB52E75AED2F044F187FD71FDFC880 /* ArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfNumberOnly.swift; sourceTree = ""; }; - 466D426E7AA31C27ABC601DD606EF126 /* JSONEncodableEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodableEncoding.swift; path = PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift; sourceTree = ""; }; - 46A00B403166BEF9EE215F6CB59BE9A6 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 475EFFB863F38801DE73965C1438E2FF /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; + 451D13FDA61BDE9EB91BBC6CEA52AED4 /* PromiseKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.xcconfig; sourceTree = ""; }; + 456356DFF7271B4F562B7F04E03E3CA8 /* FakeAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeAPI.swift; sourceTree = ""; }; + 45FB2502919E80623D265FE19C0A8FC4 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 4667C7609366DAC2FC770F6565F7F2A2 /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; + 46A00B403166BEF9EE215F6CB59BE9A6 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_SwaggerClient.framework; path = "Pods-SwaggerClient.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; 47F1D5162720B2001CA614017A1ACE90 /* join.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; - 48CCB9793CCE13A24831B3E01B29171A /* PromiseKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-prefix.pch"; sourceTree = ""; }; - 4A0977DBA9BAE46013DFD65E4400A0CB /* ReadOnlyFirst.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ReadOnlyFirst.swift; sourceTree = ""; }; - 4AC04C8B5F4B690622341DB807DAEB0B /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 48B406C5392E8AC40762B8EDE6DF1FE8 /* PromiseKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-prefix.pch"; sourceTree = ""; }; + 49BB1DA804C4AA7D9FEF0DC43604CCCE /* Fake_classname_tags123API.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Fake_classname_tags123API.swift; sourceTree = ""; }; 4DD27DB5AB64425B97113FA8D5A10F19 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 4EB94F5F2FE938ECEA46481E25FFA28F /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; + 4F72B7A542B1D04D38B262F407D0F92F /* SpecialModelName.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SpecialModelName.swift; sourceTree = ""; }; 4F8D293ABA4E6DE8B257C7E9899F1B08 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; - 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + 51830C53E0E76A54309CE2137E716625 /* AnotherfakeAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AnotherfakeAPI.swift; sourceTree = ""; }; 54DD29EE59FE04DF98E96700B3A276DB /* join.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = join.swift; path = Sources/join.swift; sourceTree = ""; }; - 5AE839994FB9B18B77FC95BCC9594683 /* OuterComposite.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterComposite.swift; sourceTree = ""; }; - 5B8F990A8905B95231C6D1955750D23C /* Client.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Client.swift; sourceTree = ""; }; - 5EB640315A574EA2C8E4584499B31A44 /* OuterString.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterString.swift; sourceTree = ""; }; + 55CCB86279C9704891B8B855CA6380F6 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; + 584CE59DFDF2D30A308478C17A426ADA /* ArrayTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayTest.swift; sourceTree = ""; }; + 5EF8BA4CB172F8F6925C18B674169419 /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; 5F434ADE4363A510D2EFDCE14A0C5746 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; - 607281BBD24DC152F24F58E6046F4652 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 60347AB0041CEAF3AFE665EDD5ED3839 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; 6456A8E3DB29C967B8479EA4438C76F3 /* PromiseKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PromiseKit.h; path = Sources/PromiseKit.h; sourceTree = ""; }; 645D2C8A204D8C820EEF9684DC5A65F8 /* fwd.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = fwd.h; path = Sources/fwd.h; sourceTree = ""; }; 64759A200040719DDE024A0F1BCDDDEE /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; - 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; + 670103307A767288F991B17974F3E258 /* ApiResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ApiResponse.swift; sourceTree = ""; }; + 697B1649F70C9355E6ED995300DBBA28 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIs.swift; path = PetstoreClient/Classes/Swaggers/APIs.swift; sourceTree = ""; }; 6B9A5CB4B436C4A88BA49990C94DB065 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; - 6C68BF2CC332C9D6485B777BA7C063AE /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; - 6D7294312CFFF12B79A7AD2E8D219344 /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PromiseKit.modulemap; sourceTree = ""; }; + 6CAF4F2E2C16A07E038AAA59349BBCD9 /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireImplementations.swift; path = PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift; sourceTree = ""; }; + 6F80C8976AE5FBE0927AD59150439B97 /* AnimalFarm.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AnimalFarm.swift; sourceTree = ""; }; + 712969C66751DDCC0D484F06819ADFAF /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; 714D784CFA6CB99C3B07B03487960BE0 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; - 7417953898146193F86A165CD5F3AF4A /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; + 721957E37E3EE5DB5F8DBF20A032B42A /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; + 76645699475D3AB6EB5242AC4D0CEFAE /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; 7824BE1937712800889974B222CAB1AD /* GlobalState.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GlobalState.m; path = Sources/GlobalState.m; sourceTree = ""; }; + 791E26F1F38D683DDDDF5B5A4B3D6607 /* MixedPropertiesAndAdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MixedPropertiesAndAdditionalPropertiesClass.swift; sourceTree = ""; }; 7AE857E00E364AD3F18C2C39D49D6DDD /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; - 7C6145F09A87143B7FC501BE989C8BBD /* FakeAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeAPI.swift; sourceTree = ""; }; - 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 7EA034E64EC60C1FCC5609CA9962CD51 /* CodableHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CodableHelper.swift; path = PetstoreClient/Classes/Swaggers/CodableHelper.swift; sourceTree = ""; }; + 7DEE2B177461F2E7FC327D113FEC55D4 /* List.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = List.swift; sourceTree = ""; }; 80933905730AC186F9CA86852B3817E6 /* AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AnyPromise.h; path = Sources/AnyPromise.h; sourceTree = ""; }; - 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; - 854F6A83AC5201A267F39995BF249D32 /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireImplementations.swift; path = PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift; sourceTree = ""; }; - 8689097AED0350F905AFA5B0962FA969 /* Animal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Animal.swift; sourceTree = ""; }; - 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; - 87DCB85380B2EC22CFE743BEDE7E4114 /* Return.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Return.swift; sourceTree = ""; }; - 88EC57640E276EA2387256530FB1F868 /* EnumArrays.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumArrays.swift; sourceTree = ""; }; - 897799EBBCCE802354256F9E7984C2CF /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; - 8B87E0BA794A79025212F37D32449C63 /* List.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = List.swift; sourceTree = ""; }; - 8BBF3490280C4ED53738743F84C890BC /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 814471C0F27B39D751143F0CD53670BD /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 828ED4B097AAB98D5568D37B8AECAFD0 /* ClassModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ClassModel.swift; sourceTree = ""; }; + 84B5DCFB56EC99326DEBD055A032458E /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; + 896B006368E7DC47A51391033A97C2EE /* ReadOnlyFirst.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ReadOnlyFirst.swift; sourceTree = ""; }; + 8BBF3490280C4ED53738743F84C890BC /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_SwaggerClientTests.framework; path = "Pods-SwaggerClientTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 8C78CDA7E4BB301D917FE7CFBD2457EF /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIHelper.swift; path = PetstoreClient/Classes/Swaggers/APIHelper.swift; sourceTree = ""; }; + 8E3B882B966B7AF813A56A7DA9DA1F1C /* Name.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Name.swift; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; 947066689D96D035F88E7408FA47E193 /* Promise+AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+AnyPromise.swift"; path = "Sources/Promise+AnyPromise.swift"; sourceTree = ""; }; 948BFEDB052F09AD8DAE3BD3CB286673 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; 9585493102C1567226760B6BACFDF648 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; - 95DA780B317CD76B87D2843B3922D627 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; - 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - 9776B33259DFB803A3E6D9573FA3DE3E /* FormatTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FormatTest.swift; sourceTree = ""; }; + 987E88064EF735B91468D5018C18E261 /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Extensions.swift; path = PetstoreClient/Classes/Swaggers/Extensions.swift; sourceTree = ""; }; + 98A8E010F6244706560DDC29B122EBAF /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + 9D08EC9B39FEBA43A5B55DAF97AAEBE9 /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; + 9D780FDAD16A03CC25F4D6F3317B9423 /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; 9E9E772008F75FBB98AEE83B59F519A9 /* when.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = when.m; path = Sources/when.m; sourceTree = ""; }; A03102A2289886143D394C1EEF173C69 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - A9930F8E68307FDF3470DAFB398895B2 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIHelper.swift; path = PetstoreClient/Classes/Swaggers/APIHelper.swift; sourceTree = ""; }; + A08C7F48AC7ABF4E88804808C4EB68F1 /* ArrayOfArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfArrayOfNumberOnly.swift; sourceTree = ""; }; + A145777600D2D0E2B9427EEE317DF443 /* FakeClassnameTags123API.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeClassnameTags123API.swift; sourceTree = ""; }; + A16286911EF2D17072D77A2B43E34006 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + AC665263E59F937C09C52DBC4851F44F /* OuterNumber.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterNumber.swift; sourceTree = ""; }; ACDBB9A0818694ED3F5545A2102E7624 /* dispatch_promise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = dispatch_promise.m; path = Sources/dispatch_promise.m; sourceTree = ""; }; - AD3B511F5C43568AAFBA2714468F9FD5 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + AD15E529B026F88FF8EAE32BD84D468D /* OuterBoolean.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterBoolean.swift; sourceTree = ""; }; + AD3B511F5C43568AAFBA2714468F9FD5 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = PromiseKit.framework; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; AE6E736FF5D4320FE1647DB1724C14B8 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; - B5DF7C9C577375BE47CAE380DE3EBE19 /* HasOnlyReadOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HasOnlyReadOnly.swift; sourceTree = ""; }; + AE8315D9D127E9BAC2C7256DB40D1D6D /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + AF3A2EA92DAC72BC0CED7B12F16198BD /* Model200Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Model200Response.swift; sourceTree = ""; }; + B28DC9FF9278F92F178AC7F416FBEF3E /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; + B4F28D074D15DD5B49DC39B3706C7C87 /* FormatTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FormatTest.swift; sourceTree = ""; }; B6AFE5B442894FF7BEA9ECAB0A39B4AD /* after.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = after.swift; path = Sources/after.swift; sourceTree = ""; }; - BA7C170F1E6A7A846F3D1C4BF9F78EAA /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; + B988BD8876FEE563F8D7A6E2534BA48B /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; + B99164AE8FDE28FAD698B280AC716F77 /* ArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfNumberOnly.swift; sourceTree = ""; }; BC1CEE597A54C622C960B36A5EC2FA0F /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; - BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; - C0C60220F2C965335A15C6C5688ACE4F /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; - C3102957D0FBF5FFA80969BB2A15F8FF /* ApiResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ApiResponse.swift; sourceTree = ""; }; - C3153AF6539569349FDEA90444438B8A /* AdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AdditionalPropertiesClass.swift; sourceTree = ""; }; - C3862A83F9BE857B1E903ABBBDE37EF7 /* AnimalFarm.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AnimalFarm.swift; sourceTree = ""; }; - C3941FB77CA24840ADF5671D16FE460C /* EnumTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumTest.swift; sourceTree = ""; }; - C4B3F69D54C19FC502362EEE3544ECA0 /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; - C7E7932024A79370E61700F5FD439D37 /* SpecialModelName.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SpecialModelName.swift; sourceTree = ""; }; + BFD9B6C73F406E259D12AAD66EB86E3A /* HasOnlyReadOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HasOnlyReadOnly.swift; sourceTree = ""; }; + C26CC9E49237A04F52DC71125A1756AB /* Client.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Client.swift; sourceTree = ""; }; + C3036A4C6739CD7F9D802133405FB095 /* NumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NumberOnly.swift; sourceTree = ""; }; C8A3F20B5239DF2DF6CB987D4827C198 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; - C925A1EF89E6AF23AE6EA4BA515A6E11 /* ClassModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ClassModel.swift; sourceTree = ""; }; C9CE45709BBC984B7998B833B10FC058 /* AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; + C9F529192DED719D7A55A3E804866F26 /* OuterComposite.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterComposite.swift; sourceTree = ""; }; CA6251246DA0044C165AC891CDE64344 /* hang.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = hang.m; path = Sources/hang.m; sourceTree = ""; }; + CAF6F32F117197F6F08B477687F09728 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; CB66B121BF9B4DF48FE2F6A4D044C443 /* AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AnyPromise.m; path = Sources/AnyPromise.m; sourceTree = ""; }; - D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; - D54B91C81FC091E900319969 /* FakeClassnameTags123API.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FakeClassnameTags123API.swift; sourceTree = ""; }; - D54B91C91FC091E900319969 /* AnotherfakeAPI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnotherfakeAPI.swift; sourceTree = ""; }; + CF1ECC5499BE9BF36F0AE0CE47ABB673 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; + CFA4F581E074596AB5C3DAF3D9C39F17 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; + D47B812D78D0AE64D85D16A96840F8C4 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; + D752057107F19596D3B8EA574206B2F2 /* OuterString.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterString.swift; sourceTree = ""; }; D75CBCB14282D5EBA5A424CCF0655C2A /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; DA33807992507937BA2869E4D72BA073 /* Zalgo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Zalgo.swift; path = Sources/Zalgo.swift; sourceTree = ""; }; - DB3DDF6C3277994828CD09F3155BB74E /* JSONEncodingHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodingHelper.swift; path = PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift; sourceTree = ""; }; - DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; DE689938DB1BB3BAF7C98928CB02978A /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; - DF26681AB7FB981F237CD8EA4F059708 /* MapTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MapTest.swift; sourceTree = ""; }; - E0A482A15F21B4BC206B31E7A0FAB79F /* Capitalization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Capitalization.swift; sourceTree = ""; }; - E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; - E1FF93AC280A80800873A20A8F72AD29 /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; - E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; + E28B79A691A2192E2A8595ACB60CC54C /* Dog.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Dog.swift; sourceTree = ""; }; + E564E86B6F817ED6259E08FB2B589CAA /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + E5EB60B9D147E1DCD36D55283254A515 /* JSONEncodableEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodableEncoding.swift; path = PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift; sourceTree = ""; }; + E63746E0EEDB9AB11F3F623A63F36BB3 /* PromiseKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-umbrella.h"; sourceTree = ""; }; + E708155DC6E87EA22044EC19AB55DD05 /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = PromiseKit.modulemap; sourceTree = ""; }; E775A7621846699F1A762DB966B3DC48 /* State.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = State.swift; path = Sources/State.swift; sourceTree = ""; }; - E7B845A9435BD8A5A34664D1A66B8484 /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; - E80A16C989615AAE419866DB4FD10185 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - EB834CA4A0478028D959D9EBD119D953 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E80A16C989615AAE419866DB4FD10185 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + EC6A834DBFB72DAA5CF0C32268CDF605 /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = PetstoreClient/Classes/Swaggers/Configuration.swift; sourceTree = ""; }; EEA7D6AB49001069ED310CBCA8FCBB44 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; - F05D3E8C18F8C0EF732558438FAA421A /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Extensions.swift; path = PetstoreClient/Classes/Swaggers/Extensions.swift; sourceTree = ""; }; - F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; + F1ED5AD8A7A28479CDC87C72B75010ED /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + F388A1ADD212030D9542E86628F22BD6 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; + F3E1116FA9F9F3AFD9332B7236F6E711 /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; + F46B1129B323D17632F7089F71632F60 /* JSONEncodingHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodingHelper.swift; path = PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift; sourceTree = ""; }; F48DFEE4376C36D6CF4C7DBFEBF91F45 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; - FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; - FE7B50737921DC202987A0E4A1665B90 /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + F4BB3B2146310CA18C30F145BFF15BD9 /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; + F8FCC3BC0A0823C3FF68C4E1EF67B2FD /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; + FB0F6DF945AB4286D73C45A2139ED7B3 /* Return.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Return.swift; sourceTree = ""; }; + FC15A6FFC961DC8B56D9DD9150014C38 /* PetstoreClient.podspec */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; path = PetstoreClient.podspec; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + FD18CDAD22507BB2C69589FD60138F66 /* Capitalization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Capitalization.swift; sourceTree = ""; }; + FDBB687EF1CAF131DB3DDD99AAE54AB6 /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + FF4FEED941249256FD7E23C19D4567AC /* EnumClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumClass.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 1B8C72E45D5881E52545540F3F4881C1 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 0B974B8BCA617D23C87619DADD37D39B /* Alamofire.framework in Frameworks */, - 3A6675715B2BD21963134EE7CB699FEE /* Foundation.framework in Frameworks */, - 989A8D9C15575595501B0525EA04B7C4 /* PromiseKit.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 1D8C8B25D2467630E50174D221B39B90 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -315,11 +308,11 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 21F0744FB2561027A81E019DEB9FBE9E /* Frameworks */ = { + 396D8A67A3003EEF737841077046D893 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 8591B80B88C9A955D3E898EEF9DA71E1 /* Foundation.framework in Frameworks */, + BEFC359220E7DA4FA032F4B3B1235AA7 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -339,6 +332,16 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + E1E915C3CCC361B9D8BCF1A0E4813C76 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 30A481BDA67CB3CF0C136A908EC50D64 /* Alamofire.framework in Frameworks */, + F149C816B083DD631AECBCADE6D525A7 /* Foundation.framework in Frameworks */, + 496F991DDEDAE92703CAA24CE165B9F3 /* PromiseKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ @@ -346,8 +349,9 @@ isa = PBXGroup; children = ( 15CB611E37F9E1F821FFD8B29C385FF9 /* CorePromise */, - A5A38542CF9E498066C1C41B2E15BBFF /* Support Files */, + 63AC42361BEBCC6C083B9575B72D40DE /* Support Files */, ); + name = PromiseKit; path = PromiseKit; sourceTree = ""; }; @@ -381,6 +385,64 @@ name = CorePromise; sourceTree = ""; }; + 1638B55794AEC03168E0A73BFA054478 /* Support Files */ = { + isa = PBXGroup; + children = ( + 1E9A49B1D85B7A38F2CAD05F245B27C3 /* Info.plist */, + 19CFD6BC7040A5BC22831D4B5EB7F793 /* PetstoreClient.modulemap */, + F1ED5AD8A7A28479CDC87C72B75010ED /* PetstoreClient.xcconfig */, + 0467D138A3101545CABA11DDD745B87B /* PetstoreClient-dummy.m */, + B28DC9FF9278F92F178AC7F416FBEF3E /* PetstoreClient-prefix.pch */, + 55CCB86279C9704891B8B855CA6380F6 /* PetstoreClient-umbrella.h */, + ); + name = "Support Files"; + path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; + sourceTree = ""; + }; + 325E314AD76E8F3FF0B03E2401003FC5 /* Models */ = { + isa = PBXGroup; + children = ( + 374D32747BDC0BDD7ACFF23F5BF910C3 /* AdditionalPropertiesClass.swift */, + 171602313BBD5AE0D5F50FFB70A96CED /* Animal.swift */, + 6F80C8976AE5FBE0927AD59150439B97 /* AnimalFarm.swift */, + 670103307A767288F991B17974F3E258 /* ApiResponse.swift */, + A08C7F48AC7ABF4E88804808C4EB68F1 /* ArrayOfArrayOfNumberOnly.swift */, + B99164AE8FDE28FAD698B280AC716F77 /* ArrayOfNumberOnly.swift */, + 584CE59DFDF2D30A308478C17A426ADA /* ArrayTest.swift */, + FD18CDAD22507BB2C69589FD60138F66 /* Capitalization.swift */, + 36EB25B2EACD40B282A658DA456B0FED /* Cat.swift */, + 84B5DCFB56EC99326DEBD055A032458E /* Category.swift */, + 828ED4B097AAB98D5568D37B8AECAFD0 /* ClassModel.swift */, + C26CC9E49237A04F52DC71125A1756AB /* Client.swift */, + E28B79A691A2192E2A8595ACB60CC54C /* Dog.swift */, + 30C1E56142D8B120BDDE2AF5CA160E22 /* EnumArrays.swift */, + FF4FEED941249256FD7E23C19D4567AC /* EnumClass.swift */, + 289EF031EA3B2CA318F7EACE05641165 /* EnumTest.swift */, + B4F28D074D15DD5B49DC39B3706C7C87 /* FormatTest.swift */, + BFD9B6C73F406E259D12AAD66EB86E3A /* HasOnlyReadOnly.swift */, + 7DEE2B177461F2E7FC327D113FEC55D4 /* List.swift */, + 38F502D93EB2D1D9C2A1283F96BFF4D2 /* MapTest.swift */, + 791E26F1F38D683DDDDF5B5A4B3D6607 /* MixedPropertiesAndAdditionalPropertiesClass.swift */, + AF3A2EA92DAC72BC0CED7B12F16198BD /* Model200Response.swift */, + 8E3B882B966B7AF813A56A7DA9DA1F1C /* Name.swift */, + C3036A4C6739CD7F9D802133405FB095 /* NumberOnly.swift */, + 4EB94F5F2FE938ECEA46481E25FFA28F /* Order.swift */, + AD15E529B026F88FF8EAE32BD84D468D /* OuterBoolean.swift */, + C9F529192DED719D7A55A3E804866F26 /* OuterComposite.swift */, + 3E5EF70E686134181F06537A75BA0FD2 /* OuterEnum.swift */, + AC665263E59F937C09C52DBC4851F44F /* OuterNumber.swift */, + D752057107F19596D3B8EA574206B2F2 /* OuterString.swift */, + 5EF8BA4CB172F8F6925C18B674169419 /* Pet.swift */, + 896B006368E7DC47A51391033A97C2EE /* ReadOnlyFirst.swift */, + FB0F6DF945AB4286D73C45A2139ED7B3 /* Return.swift */, + 4F72B7A542B1D04D38B262F407D0F92F /* SpecialModelName.swift */, + B988BD8876FEE563F8D7A6E2534BA48B /* Tag.swift */, + 32EFBC701E63AE331BC0BF170B2C1E2B /* User.swift */, + ); + name = Models; + path = PetstoreClient/Classes/Swaggers/Models; + sourceTree = ""; + }; 439566E0F816C232FEEB9A3F1FFFEF20 /* Alamofire */ = { isa = PBXGroup; children = ( @@ -401,54 +463,55 @@ 4F8D293ABA4E6DE8B257C7E9899F1B08 /* TaskDelegate.swift */, AE6E736FF5D4320FE1647DB1724C14B8 /* Timeline.swift */, 08A7F97EB8AC32E44E21839FA607D2CE /* Validation.swift */, - 8949F214ACEA39133A2AAB6508F73CC0 /* Support Files */, + 699F78D1F95BB0051EF9E96BA468FBDD /* Support Files */, ); + name = Alamofire; path = Alamofire; sourceTree = ""; }; - 60558172C46150B1CC244DFD7F495889 /* Support Files */ = { + 63AC42361BEBCC6C083B9575B72D40DE /* Support Files */ = { isa = PBXGroup; children = ( - EB834CA4A0478028D959D9EBD119D953 /* Info.plist */, - 2ACC287E45C0FCE8717A34B8ECA88A30 /* PetstoreClient.modulemap */, - FE7B50737921DC202987A0E4A1665B90 /* PetstoreClient.xcconfig */, - 3B26D25AFB2018A320BA1C7EDE3F560C /* PetstoreClient-dummy.m */, - BA7C170F1E6A7A846F3D1C4BF9F78EAA /* PetstoreClient-prefix.pch */, - C0C60220F2C965335A15C6C5688ACE4F /* PetstoreClient-umbrella.h */, + 27E9F1130735B56DF22A1439B5BA6333 /* Info.plist */, + E708155DC6E87EA22044EC19AB55DD05 /* PromiseKit.modulemap */, + 451D13FDA61BDE9EB91BBC6CEA52AED4 /* PromiseKit.xcconfig */, + 4667C7609366DAC2FC770F6565F7F2A2 /* PromiseKit-dummy.m */, + 48B406C5392E8AC40762B8EDE6DF1FE8 /* PromiseKit-prefix.pch */, + E63746E0EEDB9AB11F3F623A63F36BB3 /* PromiseKit-umbrella.h */, ); name = "Support Files"; - path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; + path = "../Target Support Files/PromiseKit"; sourceTree = ""; }; - 6BB94E4B786CD1A837889A78D18EDA58 /* Frameworks */ = { + 699F78D1F95BB0051EF9E96BA468FBDD /* Support Files */ = { isa = PBXGroup; children = ( - A03102A2289886143D394C1EEF173C69 /* Alamofire.framework */, - 4DD27DB5AB64425B97113FA8D5A10F19 /* PromiseKit.framework */, - DD9EED10DC8740383600E1BFF8D2162B /* iOS */, + 2A8ED560E3DF01E75E0272F7A1B911DD /* Alamofire.modulemap */, + 45FB2502919E80623D265FE19C0A8FC4 /* Alamofire.xcconfig */, + 60347AB0041CEAF3AFE665EDD5ED3839 /* Alamofire-dummy.m */, + E564E86B6F817ED6259E08FB2B589CAA /* Alamofire-prefix.pch */, + A16286911EF2D17072D77A2B43E34006 /* Alamofire-umbrella.h */, + 408CD558DEC1EFB9C57002ADB50665FC /* Info.plist */, ); - name = Frameworks; + name = "Support Files"; + path = "../Target Support Files/Alamofire"; sourceTree = ""; }; - 7C3C4943F0B3A9E87CCF23AA96272CB5 /* APIs */ = { + 6BB94E4B786CD1A837889A78D18EDA58 /* Frameworks */ = { isa = PBXGroup; children = ( - D54B91C91FC091E900319969 /* AnotherfakeAPI.swift */, - 7C6145F09A87143B7FC501BE989C8BBD /* FakeAPI.swift */, - D54B91C81FC091E900319969 /* FakeClassnameTags123API.swift */, - 475EFFB863F38801DE73965C1438E2FF /* PetAPI.swift */, - 897799EBBCCE802354256F9E7984C2CF /* StoreAPI.swift */, - 158D0513D0844E7FE6AEFAEE70E88618 /* UserAPI.swift */, + A03102A2289886143D394C1EEF173C69 /* Alamofire.framework */, + 4DD27DB5AB64425B97113FA8D5A10F19 /* PromiseKit.framework */, + DD9EED10DC8740383600E1BFF8D2162B /* iOS */, ); - name = APIs; - path = PetstoreClient/Classes/Swaggers/APIs; + name = Frameworks; sourceTree = ""; }; 7DB346D0F39D3F0E887471402A8071AB = { isa = PBXGroup; children = ( 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, - EDE36CDEEF568DD818B58A28C3C0DA80 /* Development Pods */, + EC52080E65FE34CBDE5F694B08BA9836 /* Development Pods */, 6BB94E4B786CD1A837889A78D18EDA58 /* Frameworks */, A1A7A33E3B583AD8CD782AFD6B69D4A0 /* Pods */, D2A28169658A67F83CC3B568D7E0E6A1 /* Products */, @@ -456,58 +519,27 @@ ); sourceTree = ""; }; - 80845DB4F55E7613E45819034AAA6B0F /* PetstoreClient */ = { + 9552BC9D547079722BECEF69D39F81A1 /* PetstoreClient */ = { isa = PBXGroup; children = ( - 854F6A83AC5201A267F39995BF249D32 /* AlamofireImplementations.swift */, - A9930F8E68307FDF3470DAFB398895B2 /* APIHelper.swift */, - 3581DEB2B2BDC3D8A0BF7C43BD317506 /* APIs.swift */, - 7EA034E64EC60C1FCC5609CA9962CD51 /* CodableHelper.swift */, - 411BB07BE03DCC7000891F6A5E62BBC6 /* Configuration.swift */, - F05D3E8C18F8C0EF732558438FAA421A /* Extensions.swift */, - 466D426E7AA31C27ABC601DD606EF126 /* JSONEncodableEncoding.swift */, - DB3DDF6C3277994828CD09F3155BB74E /* JSONEncodingHelper.swift */, - 3ED6F43B3A7602CD88ED67B9873B2036 /* Models.swift */, - 7C3C4943F0B3A9E87CCF23AA96272CB5 /* APIs */, - B7C7CFA5065F490C632218EDF496EB25 /* Models */, - 60558172C46150B1CC244DFD7F495889 /* Support Files */, + 6CAF4F2E2C16A07E038AAA59349BBCD9 /* AlamofireImplementations.swift */, + 8C78CDA7E4BB301D917FE7CFBD2457EF /* APIHelper.swift */, + 697B1649F70C9355E6ED995300DBBA28 /* APIs.swift */, + 06D5E6CDDEE294F817C22C521B562508 /* CodableHelper.swift */, + EC6A834DBFB72DAA5CF0C32268CDF605 /* Configuration.swift */, + 987E88064EF735B91468D5018C18E261 /* Extensions.swift */, + E5EB60B9D147E1DCD36D55283254A515 /* JSONEncodableEncoding.swift */, + F46B1129B323D17632F7089F71632F60 /* JSONEncodingHelper.swift */, + 2AEE7AA4D6A19965503F1889B1F44B1D /* Models.swift */, + C6898391DC18DA3449C18CD93A69078D /* APIs */, + 325E314AD76E8F3FF0B03E2401003FC5 /* Models */, + D313744EEA7BEA6ED6344DEF771433F5 /* Pod */, + 1638B55794AEC03168E0A73BFA054478 /* Support Files */, ); name = PetstoreClient; path = ../..; sourceTree = ""; }; - 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */ = { - isa = PBXGroup; - children = ( - 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */, - DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */, - 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */, - E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */, - 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */, - BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */, - D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */, - 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */, - 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */, - 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */, - ); - name = "Pods-SwaggerClient"; - path = "Target Support Files/Pods-SwaggerClient"; - sourceTree = ""; - }; - 8949F214ACEA39133A2AAB6508F73CC0 /* Support Files */ = { - isa = PBXGroup; - children = ( - 1F11D15E4489C7F4DC1171EB9F5448D0 /* Alamofire.modulemap */, - 6C68BF2CC332C9D6485B777BA7C063AE /* Alamofire.xcconfig */, - 4AC04C8B5F4B690622341DB807DAEB0B /* Alamofire-dummy.m */, - 607281BBD24DC152F24F58E6046F4652 /* Alamofire-prefix.pch */, - 95DA780B317CD76B87D2843B3922D627 /* Alamofire-umbrella.h */, - 17FF216D0378037475BAB48A20D5CB0F /* Info.plist */, - ); - name = "Support Files"; - path = "../Target Support Files/Alamofire"; - sourceTree = ""; - }; A1A7A33E3B583AD8CD782AFD6B69D4A0 /* Pods */ = { isa = PBXGroup; children = ( @@ -517,71 +549,28 @@ name = Pods; sourceTree = ""; }; - A5A38542CF9E498066C1C41B2E15BBFF /* Support Files */ = { - isa = PBXGroup; - children = ( - 34E180DB9A06BFDDA525853716B57541 /* Info.plist */, - 6D7294312CFFF12B79A7AD2E8D219344 /* PromiseKit.modulemap */, - 425268D5A6D1CD870A663BBE38B62B46 /* PromiseKit.xcconfig */, - E7B845A9435BD8A5A34664D1A66B8484 /* PromiseKit-dummy.m */, - 48CCB9793CCE13A24831B3E01B29171A /* PromiseKit-prefix.pch */, - 3C7BB9DA6D00D51D3DB475EDCFC925B3 /* PromiseKit-umbrella.h */, - ); - name = "Support Files"; - path = "../Target Support Files/PromiseKit"; - sourceTree = ""; - }; - B7C7CFA5065F490C632218EDF496EB25 /* Models */ = { + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { isa = PBXGroup; children = ( - C3153AF6539569349FDEA90444438B8A /* AdditionalPropertiesClass.swift */, - 8689097AED0350F905AFA5B0962FA969 /* Animal.swift */, - C3862A83F9BE857B1E903ABBBDE37EF7 /* AnimalFarm.swift */, - C3102957D0FBF5FFA80969BB2A15F8FF /* ApiResponse.swift */, - 1B900B675208453FB7767B0D97D50932 /* ArrayOfArrayOfNumberOnly.swift */, - 45CB52E75AED2F044F187FD71FDFC880 /* ArrayOfNumberOnly.swift */, - 30B827D77F92D24E6D24561F491F2A50 /* ArrayTest.swift */, - E0A482A15F21B4BC206B31E7A0FAB79F /* Capitalization.swift */, - 4530F24A4BDA094563779F1D4313B9E1 /* Cat.swift */, - 7417953898146193F86A165CD5F3AF4A /* Category.swift */, - C925A1EF89E6AF23AE6EA4BA515A6E11 /* ClassModel.swift */, - 5B8F990A8905B95231C6D1955750D23C /* Client.swift */, - 28F73294B64CD8821EC2467CB7F1F073 /* Dog.swift */, - 88EC57640E276EA2387256530FB1F868 /* EnumArrays.swift */, - 30E08D3E06CED1E4F2876EFA44A239ED /* EnumClass.swift */, - C3941FB77CA24840ADF5671D16FE460C /* EnumTest.swift */, - 9776B33259DFB803A3E6D9573FA3DE3E /* FormatTest.swift */, - B5DF7C9C577375BE47CAE380DE3EBE19 /* HasOnlyReadOnly.swift */, - 8B87E0BA794A79025212F37D32449C63 /* List.swift */, - DF26681AB7FB981F237CD8EA4F059708 /* MapTest.swift */, - 3FB1FE2028948C532392F549A4356FBC /* MixedPropertiesAndAdditionalPropertiesClass.swift */, - 3617A5AF85A2814F852C73FD5D575262 /* Model200Response.swift */, - 2C0EF68B5117187E979D1DE4ECDB938E /* Name.swift */, - 2A332587F10679E262455F979B3D1055 /* NumberOnly.swift */, - 24D3039E712D1279434152E805AEDA65 /* Order.swift */, - 21A143975CF52EBFEF79A307CC7CB00E /* OuterBoolean.swift */, - 5AE839994FB9B18B77FC95BCC9594683 /* OuterComposite.swift */, - 13C6EEF1D81A0C523AE569F1732AC8DC /* OuterEnum.swift */, - 0BA93068A5B18A779CC9B0FC3F685400 /* OuterNumber.swift */, - 5EB640315A574EA2C8E4584499B31A44 /* OuterString.swift */, - E1FF93AC280A80800873A20A8F72AD29 /* Pet.swift */, - 4A0977DBA9BAE46013DFD65E4400A0CB /* ReadOnlyFirst.swift */, - 87DCB85380B2EC22CFE743BEDE7E4114 /* Return.swift */, - C7E7932024A79370E61700F5FD439D37 /* SpecialModelName.swift */, - 02E62B78D97471D708B23605FCAA9EA1 /* Tag.swift */, - C4B3F69D54C19FC502362EEE3544ECA0 /* User.swift */, + DE503BFFEBBF78BDC743C8A6A50DFF47 /* Pods-SwaggerClient */, + E9EDF70990CC7A4463ED5FC2E3719BD0 /* Pods-SwaggerClientTests */, ); - name = Models; - path = PetstoreClient/Classes/Swaggers/Models; + name = "Targets Support Files"; sourceTree = ""; }; - C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { + C6898391DC18DA3449C18CD93A69078D /* APIs */ = { isa = PBXGroup; children = ( - 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */, - D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */, + 51830C53E0E76A54309CE2137E716625 /* AnotherfakeAPI.swift */, + 49BB1DA804C4AA7D9FEF0DC43604CCCE /* Fake_classname_tags123API.swift */, + 456356DFF7271B4F562B7F04E03E3CA8 /* FakeAPI.swift */, + A145777600D2D0E2B9427EEE317DF443 /* FakeClassnameTags123API.swift */, + 712969C66751DDCC0D484F06819ADFAF /* PetAPI.swift */, + 98A8E010F6244706560DDC29B122EBAF /* StoreAPI.swift */, + 364DFA113368D39E8F9FF776C3C78B11 /* UserAPI.swift */, ); - name = "Targets Support Files"; + name = APIs; + path = PetstoreClient/Classes/Swaggers/APIs; sourceTree = ""; }; D2A28169658A67F83CC3B568D7E0E6A1 /* Products */ = { @@ -596,22 +585,12 @@ name = Products; sourceTree = ""; }; - D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */ = { + D313744EEA7BEA6ED6344DEF771433F5 /* Pod */ = { isa = PBXGroup; children = ( - 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */, - 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */, - FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */, - 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */, - 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */, - 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */, - E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */, - F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */, - 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */, - 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */, + FC15A6FFC961DC8B56D9DD9150014C38 /* PetstoreClient.podspec */, ); - name = "Pods-SwaggerClientTests"; - path = "Target Support Files/Pods-SwaggerClientTests"; + name = Pod; sourceTree = ""; }; DD9EED10DC8740383600E1BFF8D2162B /* iOS */ = { @@ -622,10 +601,46 @@ name = iOS; sourceTree = ""; }; - EDE36CDEEF568DD818B58A28C3C0DA80 /* Development Pods */ = { + DE503BFFEBBF78BDC743C8A6A50DFF47 /* Pods-SwaggerClient */ = { + isa = PBXGroup; + children = ( + 814471C0F27B39D751143F0CD53670BD /* Info.plist */, + CFA4F581E074596AB5C3DAF3D9C39F17 /* Pods-SwaggerClient.modulemap */, + 76645699475D3AB6EB5242AC4D0CEFAE /* Pods-SwaggerClient-acknowledgements.markdown */, + 08BDFE9C9E9365771FF2D47928E3E79A /* Pods-SwaggerClient-acknowledgements.plist */, + F8FCC3BC0A0823C3FF68C4E1EF67B2FD /* Pods-SwaggerClient-dummy.m */, + 0AD61F8554C909A3AFA66AD9ECCB5F23 /* Pods-SwaggerClient-frameworks.sh */, + F4BB3B2146310CA18C30F145BFF15BD9 /* Pods-SwaggerClient-resources.sh */, + 32432BEBC9EDBC5E269C9AA0E570F464 /* Pods-SwaggerClient-umbrella.h */, + AE8315D9D127E9BAC2C7256DB40D1D6D /* Pods-SwaggerClient.debug.xcconfig */, + F388A1ADD212030D9542E86628F22BD6 /* Pods-SwaggerClient.release.xcconfig */, + ); + name = "Pods-SwaggerClient"; + path = "Target Support Files/Pods-SwaggerClient"; + sourceTree = ""; + }; + E9EDF70990CC7A4463ED5FC2E3719BD0 /* Pods-SwaggerClientTests */ = { isa = PBXGroup; children = ( - 80845DB4F55E7613E45819034AAA6B0F /* PetstoreClient */, + 419496CDDD7E7536CBEA02BAEE2C7C21 /* Info.plist */, + 9D08EC9B39FEBA43A5B55DAF97AAEBE9 /* Pods-SwaggerClientTests.modulemap */, + D47B812D78D0AE64D85D16A96840F8C4 /* Pods-SwaggerClientTests-acknowledgements.markdown */, + 9D780FDAD16A03CC25F4D6F3317B9423 /* Pods-SwaggerClientTests-acknowledgements.plist */, + 721957E37E3EE5DB5F8DBF20A032B42A /* Pods-SwaggerClientTests-dummy.m */, + CAF6F32F117197F6F08B477687F09728 /* Pods-SwaggerClientTests-frameworks.sh */, + F3E1116FA9F9F3AFD9332B7236F6E711 /* Pods-SwaggerClientTests-resources.sh */, + CF1ECC5499BE9BF36F0AE0CE47ABB673 /* Pods-SwaggerClientTests-umbrella.h */, + 1ACCB3378E1513AEAADC85C4036257E4 /* Pods-SwaggerClientTests.debug.xcconfig */, + FDBB687EF1CAF131DB3DDD99AAE54AB6 /* Pods-SwaggerClientTests.release.xcconfig */, + ); + name = "Pods-SwaggerClientTests"; + path = "Target Support Files/Pods-SwaggerClientTests"; + sourceTree = ""; + }; + EC52080E65FE34CBDE5F694B08BA9836 /* Development Pods */ = { + isa = PBXGroup; + children = ( + 9552BC9D547079722BECEF69D39F81A1 /* PetstoreClient */, ); name = "Development Pods"; sourceTree = ""; @@ -641,22 +656,22 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 247861DD0240A7F61EE9BD1526A71052 /* Headers */ = { + 30A4478C9173EAE8FD13FC8118D14766 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - E8AD4D7E49710B99BFD77E32C5EBFAE8 /* PetstoreClient-umbrella.h in Headers */, + 106547F65F792529AD62ADC1AC01D58F /* AnyPromise.h in Headers */, + FC35F21E2F24A684684707DAA3745F36 /* fwd.h in Headers */, + 54A8DFD3F23A65EBEBEE381B8B18107A /* PromiseKit-umbrella.h in Headers */, + 1C0634A540F1294BEFD39E8D6EC7CDDE /* PromiseKit.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - 7732E969446BF18D45DF5D7762E56585 /* Headers */ = { + 97C378F13A6642E2128BEDA858BE3C8F /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - FE73D6A3B0670590535EC0D79F4F7246 /* AnyPromise.h in Headers */, - BB3C554F09627EA5E6E36084E4AA5545 /* fwd.h in Headers */, - 02650248013496C5AB857B869C562661 /* PromiseKit-umbrella.h in Headers */, - B65BFA719D8195A2FAA0E067DE5A6DA4 /* PromiseKit.h in Headers */, + 9394F85AA6ED6214DE27966C68945180 /* PetstoreClient-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -679,13 +694,13 @@ /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ - 05AABECB91CEE9C8C520680DDD9BA9AB /* PromiseKit */ = { + 0E4534BC972F48AE7712EBE0EBE4A62A /* PromiseKit */ = { isa = PBXNativeTarget; - buildConfigurationList = EF55B259278E6A593DF7F60BDD524C1D /* Build configuration list for PBXNativeTarget "PromiseKit" */; + buildConfigurationList = 6DABECADE21FD2D0306FD65D1962D82C /* Build configuration list for PBXNativeTarget "PromiseKit" */; buildPhases = ( - 8E56111DCEAA0843CC2406F80FC6AC8E /* Sources */, - 21F0744FB2561027A81E019DEB9FBE9E /* Frameworks */, - 7732E969446BF18D45DF5D7762E56585 /* Headers */, + 5EF303B4A0E59B78FA3C6D66CAA3FEBF /* Sources */, + 396D8A67A3003EEF737841077046D893 /* Frameworks */, + 30A4478C9173EAE8FD13FC8118D14766 /* Headers */, ); buildRules = ( ); @@ -713,19 +728,19 @@ productReference = E80A16C989615AAE419866DB4FD10185 /* Alamofire.framework */; productType = "com.apple.product-type.framework"; }; - BEF02C72A6656158D171985B49ABDD62 /* PetstoreClient */ = { + A9570E2CBF2CCB6FF2D1D0BCBC2C1DA4 /* PetstoreClient */ = { isa = PBXNativeTarget; - buildConfigurationList = 9EAF730020668F908855C7CE58AD558B /* Build configuration list for PBXNativeTarget "PetstoreClient" */; + buildConfigurationList = 4E531EDABB05EEFCF77F621FDF76EE61 /* Build configuration list for PBXNativeTarget "PetstoreClient" */; buildPhases = ( - 4F6B3944D9B6D707C48F41C03EEE78C5 /* Sources */, - 1B8C72E45D5881E52545540F3F4881C1 /* Frameworks */, - 247861DD0240A7F61EE9BD1526A71052 /* Headers */, + 7C13D0A0C9E1E42C36CA621CFE601D4B /* Sources */, + E1E915C3CCC361B9D8BCF1A0E4813C76 /* Frameworks */, + 97C378F13A6642E2128BEDA858BE3C8F /* Headers */, ); buildRules = ( ); dependencies = ( - 673D77682E593868E01C5FA765287285 /* PBXTargetDependency */, - 54BB4F0799462BDB807AAD5F3BF68BFD /* PBXTargetDependency */, + 065C9E6CD63970D95C755C83B4B598AE /* PBXTargetDependency */, + 49E753677AE8DE06E40BA119B204E0FD /* PBXTargetDependency */, ); name = PetstoreClient; productName = PetstoreClient; @@ -775,8 +790,8 @@ D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { isa = PBXProject; attributes = { - LastSwiftUpdateCheck = 0830; - LastUpgradeCheck = 0700; + LastSwiftUpdateCheck = 0930; + LastUpgradeCheck = 0930; }; buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; compatibilityVersion = "Xcode 3.2"; @@ -791,10 +806,10 @@ projectRoot = ""; targets = ( 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, - BEF02C72A6656158D171985B49ABDD62 /* PetstoreClient */, + A9570E2CBF2CCB6FF2D1D0BCBC2C1DA4 /* PetstoreClient */, E5B96E99C219DDBC57BC27EE9DF5EC22 /* Pods-SwaggerClient */, F3DF8DD6DBDCB07B04D7B1CC8A462562 /* Pods-SwaggerClientTests */, - 05AABECB91CEE9C8C520680DDD9BA9AB /* PromiseKit */, + 0E4534BC972F48AE7712EBE0EBE4A62A /* PromiseKit */, ); }; /* End PBXProject section */ @@ -825,90 +840,91 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 4F6B3944D9B6D707C48F41C03EEE78C5 /* Sources */ = { + 5EF303B4A0E59B78FA3C6D66CAA3FEBF /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 00E45C819B259C722DA2BF90EE63DDE6 /* AdditionalPropertiesClass.swift in Sources */, - 21E703668E91D10CECB8BBE59650D58F /* AlamofireImplementations.swift in Sources */, - 1F4886332EE9958B4953893705FF9246 /* Animal.swift in Sources */, - E9783E1D3A6A0CD9CF2ACCA74A89CC8F /* AnimalFarm.swift in Sources */, - E80880F475CC14AFB6795F1451DDE2B4 /* APIHelper.swift in Sources */, - D54B91CB1FC091E900319969 /* AnotherfakeAPI.swift in Sources */, - 38C508C4B73F4EEF12972C4DEBBB59BD /* ApiResponse.swift in Sources */, - 7F7153A9E140DB803EFB19D4C3D2408A /* APIs.swift in Sources */, - 4E875FE97DC4CFCD45EF180B1930BA87 /* ArrayOfArrayOfNumberOnly.swift in Sources */, - 30F26AB48B6038D292000A176A0A25D2 /* ArrayOfNumberOnly.swift in Sources */, - C77EFC1A12788F4EC02C8F08DF687A1B /* ArrayTest.swift in Sources */, - C9004CA15837C724215DE3E1A7AB42AB /* Capitalization.swift in Sources */, - 1392D80ECC22365B4831BC95032F0F0B /* Cat.swift in Sources */, - DBFDFCF61E2F2C7A49FD50B9222E3495 /* Category.swift in Sources */, - 3149FCFDA10385D31F93F2F781AA34D0 /* ClassModel.swift in Sources */, - 5491C5AA65355E89637F78928E52D24C /* Client.swift in Sources */, - BA9D88BD67EA9ACBDE9FEBF06E4FBD4D /* CodableHelper.swift in Sources */, - 453006CD439DABF8B2B378F4A40AC1CA /* Configuration.swift in Sources */, - AA022DF933E15BC6AF9A8C157370CF96 /* Dog.swift in Sources */, - 58F07EB0BF05A369A3952852632562F6 /* EnumArrays.swift in Sources */, - 0E4F6AB01CA15D7ACE27641BA3803ACE /* EnumClass.swift in Sources */, - 34104D7277F8474FCBB80637A8364337 /* EnumTest.swift in Sources */, - 884B23FB0C4EA228B4694F191D531090 /* Extensions.swift in Sources */, - 2AA4FCEA014BFBBBD56C909C02B98A77 /* FakeAPI.swift in Sources */, - D9FEE02D3C00097A882DCF9AF60C4FDC /* FormatTest.swift in Sources */, - 5742106D27D324737B72F32CBAC98924 /* HasOnlyReadOnly.swift in Sources */, - B6FE8649C8F2D879752D6CC0BAA7D8D3 /* JSONEncodableEncoding.swift in Sources */, - 4D46B19B21C17385C251DBFD6B5CC9B5 /* JSONEncodingHelper.swift in Sources */, - FD5C92BE0C43E605D5AED2BEE74BC595 /* List.swift in Sources */, - A9A1683640F2AEEE1463B4564735F52C /* MapTest.swift in Sources */, - 9621FE3846B399A31C9D874A68B814EA /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */, - DDF666793202988950DA52A8C528C076 /* Model200Response.swift in Sources */, - 6FABE818191D2C7497B657CB717435A9 /* Models.swift in Sources */, - 8628572254ED43AD0FB157E20D3B6DCF /* Name.swift in Sources */, - C2C77FE3B30FA828B5A6F8611C84AB03 /* NumberOnly.swift in Sources */, - 812B1864BB988DE4C71DE5755B9A7D1C /* Order.swift in Sources */, - D54935D8A773E7BC8DED0861487D5CEB /* OuterBoolean.swift in Sources */, - C807A7AC785D77909FF2288E66669889 /* OuterComposite.swift in Sources */, - F9D35B36A805D504C9383C5743874D23 /* OuterEnum.swift in Sources */, - 4CEC13EBEA756DB01D9EDD495477148E /* OuterNumber.swift in Sources */, - 32495BBAAED67B464B26E37EFC43BFAA /* OuterString.swift in Sources */, - AF0CAB7D38117E91D76835CE62FE9530 /* Pet.swift in Sources */, - C57A01A8A02024DD3C4F013AB8F41F71 /* PetAPI.swift in Sources */, - D54B91CA1FC091E900319969 /* FakeClassnameTags123API.swift in Sources */, - E86EED1FA38087909568DED335E7B9A5 /* PetstoreClient-dummy.m in Sources */, - EF15BEAF1A002B97A226F9AF3D3C0F26 /* ReadOnlyFirst.swift in Sources */, - 7DBDDA5406CB59867FC877F1032BC905 /* Return.swift in Sources */, - A7803F0032BE57E83C9E1CC15442058E /* SpecialModelName.swift in Sources */, - 36C43C6EB14FFC6C23618D2EE8C6D64B /* StoreAPI.swift in Sources */, - 60E0243A7018DE1E7755825685D30151 /* Tag.swift in Sources */, - 50FC50E41FA283FD8EACEED8EB7CC15C /* User.swift in Sources */, - E52BCAD4A070EEAA1EA08F2D299F4EDB /* UserAPI.swift in Sources */, + 36F8AE4A7F55750F441C4EA540D1699C /* after.m in Sources */, + 27C0638829CB61F69ACAA8ADBEFB18F8 /* after.swift in Sources */, + E8381C638D5A359B3253A52097E8B36A /* AnyPromise.m in Sources */, + 55692168300BC109D310F93B530B4132 /* AnyPromise.swift in Sources */, + 80BF18A2B7CCB1144BDF94B1B9C94F4C /* dispatch_promise.m in Sources */, + 04383899005EE36AF21F761D7DC80E95 /* DispatchQueue+Promise.swift in Sources */, + 2ADC297B4E6F3FF3B8FE90461C80DC81 /* Error.swift in Sources */, + F97FBC27216FCA32291E371DC468FCFA /* GlobalState.m in Sources */, + 0AAA2459130A15FAB0A059B2C8D538A9 /* hang.m in Sources */, + 8117E1FE605C93F0136EF1FA853AE6DD /* join.m in Sources */, + C148EBC0FC3237381FFE4C0848DCAD0B /* join.swift in Sources */, + 4D2ECA6C094192F32B0B6F65481D7E47 /* Promise+AnyPromise.swift in Sources */, + D725087C0D7C1C9A7A55AB21895AC621 /* Promise+Properties.swift in Sources */, + 7FCA54A30C9BD117FC96CC045BBB58BE /* Promise.swift in Sources */, + B207CF0DA3B3545959B5B95FBBB53D9B /* PromiseKit-dummy.m in Sources */, + 84BA25DC929E84CEEA3A86A6A6168175 /* race.swift in Sources */, + 70BFDB7E47A8CCB22B535EDCBDAABC7C /* State.swift in Sources */, + 1F1E70B6B892CFE7E8D03B3890D05C5A /* when.m in Sources */, + 6997A0FD680C0A48DEF678CED18DA37B /* when.swift in Sources */, + 1A6464D1BF86829B60AA7F767B2B6228 /* wrap.swift in Sources */, + FCB76B4B93511BE442511A358CDA4779 /* Zalgo.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; - 8E56111DCEAA0843CC2406F80FC6AC8E /* Sources */ = { + 7C13D0A0C9E1E42C36CA621CFE601D4B /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - B40BA9338A0622CC69161949F42E0ADE /* after.m in Sources */, - A3B4F53480EF96400D782F3507A42573 /* after.swift in Sources */, - A6FAEDD331C7E9BD959076F2CC466B5A /* AnyPromise.m in Sources */, - 85543B6F540EED8FFF82015FED6CB68B /* AnyPromise.swift in Sources */, - FC0B3667BB40C86FC84990EEDF29B534 /* dispatch_promise.m in Sources */, - 9DCADBA52F4BA9C2BCDD2AD9FC39291E /* DispatchQueue+Promise.swift in Sources */, - 669789618901F2B104F686A8A44E4F23 /* Error.swift in Sources */, - 95DD56D8244A0F779EA3D24617389DFA /* GlobalState.m in Sources */, - 46C3E70BD716E72351EA9828A496E59A /* hang.m in Sources */, - 0BC6EA4CC7B942917A160339B54748B6 /* join.m in Sources */, - 6939CF29A58F770558A46D229F33CDEF /* join.swift in Sources */, - BE111800D151B74E9EB6CFFA5375A378 /* Promise+AnyPromise.swift in Sources */, - 878E6E228B4A3D2725656142AA379D7F /* Promise+Properties.swift in Sources */, - D6184AB54A12F4F580FE7766FFD1A491 /* Promise.swift in Sources */, - 888EF901304106608916A05E6EC6A0A0 /* PromiseKit-dummy.m in Sources */, - C36D10DCACB58234D9ADAE75457BB1F7 /* race.swift in Sources */, - 98859B984F0B8D1BA8C419626A541DDF /* State.swift in Sources */, - CAA786E247A67408ED8FDDD3BD9EACC3 /* when.m in Sources */, - FCB75043BDF47C08F944EFD06D4636D9 /* when.swift in Sources */, - B319CCF9C8F0F08FADAEA89F9655B54E /* wrap.swift in Sources */, - 34C9317929C1DA5F022B5AEC56DED275 /* Zalgo.swift in Sources */, + 2CFA4F6DB943A88101EC5E33612F3D3A /* AdditionalPropertiesClass.swift in Sources */, + 631846166C39D7961C0FC2420A814D5D /* AlamofireImplementations.swift in Sources */, + A564637BF264BB4CFB6FEF9CB75104A1 /* Animal.swift in Sources */, + BEEF2C5F2E966C2177FE98B2D72CF0BF /* AnimalFarm.swift in Sources */, + 75E75F96CB55F0D28EE06BAB415C26DC /* AnotherfakeAPI.swift in Sources */, + 7AE27271C19BB4061041C31FCA3244D2 /* APIHelper.swift in Sources */, + D61DF6FE79C6EB404622E9BB8BA73D0E /* ApiResponse.swift in Sources */, + B5AB1B6A32A9C6089D4C6B45C0F62908 /* APIs.swift in Sources */, + D88DA7B51E85EFDE66A1E2FB8E15A961 /* ArrayOfArrayOfNumberOnly.swift in Sources */, + E0D2E9BDF0D339F6DB14A81CF4BDB0CE /* ArrayOfNumberOnly.swift in Sources */, + 50535053DF0B148D8D55C84AACE3E821 /* ArrayTest.swift in Sources */, + 52D5D882F7A76CCC2E82CEC51E4C4A8F /* Capitalization.swift in Sources */, + CF6B474D37B11F62B01420187A4BC8E8 /* Cat.swift in Sources */, + F200D84ABF9E46CE68D20FA0107CB998 /* Category.swift in Sources */, + A56117A0D1F9C17CDAEC93D025808F95 /* ClassModel.swift in Sources */, + 28A61491F92263C04AC52DDB7D3D7C5E /* Client.swift in Sources */, + 98E6C302C43D21D3C7E655C6AB628229 /* CodableHelper.swift in Sources */, + 1103E43C29C4C4880211E7F883882F70 /* Configuration.swift in Sources */, + 2D1EC3F916AA171A159217B17E1DC3A5 /* Dog.swift in Sources */, + CE1E54F275C78733C1920B8843E0FE7F /* EnumArrays.swift in Sources */, + BECEC463EA228A617DDC97A74DC82317 /* EnumClass.swift in Sources */, + 2C2B0BFA01ABB26BC0961FDCEBCF9193 /* EnumTest.swift in Sources */, + 221F18103190719148CA55FA85959C89 /* Extensions.swift in Sources */, + 2613421691DFA013A440D1545EE747F9 /* Fake_classname_tags123API.swift in Sources */, + 083C731FF7E5782D19029803B9C23DE8 /* FakeAPI.swift in Sources */, + ACB6244F92A66923FBDE06DB52FC0E58 /* FakeClassnameTags123API.swift in Sources */, + B084B1F97F44DD44E97DE9609E63339C /* FormatTest.swift in Sources */, + DCA4F98E74966A61AB0694E91D2059E8 /* HasOnlyReadOnly.swift in Sources */, + 777BF05C3DD2E08DB3E3EED5F97A0CD8 /* JSONEncodableEncoding.swift in Sources */, + 802E48AE09C6A80FD22638D72C73A747 /* JSONEncodingHelper.swift in Sources */, + BAA40BFDD985C530D27C930B3C68B1B1 /* List.swift in Sources */, + F80BFCE54D77C81CA17F4CEEBEBE394D /* MapTest.swift in Sources */, + 31582924647B36C90C9B7763F14905F8 /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */, + 4818A1E024F6FAE56EFCC63F1C0F9631 /* Model200Response.swift in Sources */, + 095BBCE1E728245C9E4E162B0FE4BB6A /* Models.swift in Sources */, + 7BFA5408D6C0495B19C0CDDEA71474D5 /* Name.swift in Sources */, + A86F3B3FE87D83AF99AB9BFC8155628B /* NumberOnly.swift in Sources */, + FC84AAA8BB9ED0767994FAA4FC65EE71 /* Order.swift in Sources */, + 64FBE4A1A786C4AFE12ADD42ECD1572A /* OuterBoolean.swift in Sources */, + DBD92C6CA90C0BD1C4C06C2BE18919DA /* OuterComposite.swift in Sources */, + A4CF090C8C8CAB1F0DA8DB338C80F144 /* OuterEnum.swift in Sources */, + 0A2E76BD89D6BF6F8F889FAFEF599199 /* OuterNumber.swift in Sources */, + 18E0A0C81B42135BD9A73D1670B982D7 /* OuterString.swift in Sources */, + BD32F9E3B06BF67B0247C821095F7247 /* Pet.swift in Sources */, + 3CFA2361C8B43583460324BE5C3F0AA2 /* PetAPI.swift in Sources */, + 21D5CF155AB37729819479C01C692275 /* PetstoreClient-dummy.m in Sources */, + 667D55108CF6FE31F77C42480691A11F /* ReadOnlyFirst.swift in Sources */, + 65FFD0F2A18B865A83654491E2822133 /* Return.swift in Sources */, + 405B9F95A650E2FEC0ED1BCAE7682AA7 /* SpecialModelName.swift in Sources */, + F3365947E0B9BD60F15F14C0C2F644E8 /* StoreAPI.swift in Sources */, + 3D7779C784C66A0C30436BD2CA2C0F40 /* Tag.swift in Sources */, + B0556940CFFF7904CA9C2CAB1AF71FB3 /* User.swift in Sources */, + 0A7BAE5F9B5FF377168750D402C2D785 /* UserAPI.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -931,6 +947,12 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ + 065C9E6CD63970D95C755C83B4B598AE /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; + targetProxy = 4F56515656F716821CBADACB7A9CB467 /* PBXContainerItemProxy */; + }; 1C76F9E08AAB9400CF7937D3DBF4E272 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; @@ -940,246 +962,237 @@ 328C6C7DF03199CFF8F5B47C39DEE2BC /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = PromiseKit; - target = 05AABECB91CEE9C8C520680DDD9BA9AB /* PromiseKit */; + target = 0E4534BC972F48AE7712EBE0EBE4A62A /* PromiseKit */; targetProxy = F4F5C9A84714BE23040A5FB7588DA6BD /* PBXContainerItemProxy */; }; 405120CD9D9120CBBC452E54C91FA485 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = PetstoreClient; - target = BEF02C72A6656158D171985B49ABDD62 /* PetstoreClient */; + target = A9570E2CBF2CCB6FF2D1D0BCBC2C1DA4 /* PetstoreClient */; targetProxy = B173CFF2A1174933D7851E8CE1CA77AB /* PBXContainerItemProxy */; }; - 54BB4F0799462BDB807AAD5F3BF68BFD /* PBXTargetDependency */ = { + 49E753677AE8DE06E40BA119B204E0FD /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = PromiseKit; - target = 05AABECB91CEE9C8C520680DDD9BA9AB /* PromiseKit */; - targetProxy = 2A6F85761AF8DEABF6BBF52FD80B83C1 /* PBXContainerItemProxy */; - }; - 673D77682E593868E01C5FA765287285 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Alamofire; - target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; - targetProxy = 0166D6CEA46A405AF6440470518778BB /* PBXContainerItemProxy */; + target = 0E4534BC972F48AE7712EBE0EBE4A62A /* PromiseKit */; + targetProxy = 8CC739769B7ED206269C0591EE53BD65 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ - 007503D8498115ADB100193B3AD6BACC /* Release */ = { + 0A501A275C2C77F82FD28A347B80496E /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; + baseConfigurationReference = F1ED5AD8A7A28479CDC87C72B75010ED /* PetstoreClient.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.2; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_SwaggerClient; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + PRODUCT_NAME = PetstoreClient; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Release; + name = Debug; }; - 077C4BB7DBEAA715DED46C057DC8051C /* Release */ = { + 1928FD2BA1177E86A2DAF2641C8755AA /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 6C68BF2CC332C9D6485B777BA7C063AE /* Alamofire.xcconfig */; + baseConfigurationReference = FDBB687EF1CAF131DB3DDD99AAE54AB6 /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = Alamofire; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; - 2C23BEE8A5AA6F2B41B70CC48B77C8AF /* Release */ = { + 1DF48E764052158CE8AC40DB7B84172C /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = FE7B50737921DC202987A0E4A1665B90 /* PetstoreClient.xcconfig */; + baseConfigurationReference = AE8315D9D127E9BAC2C7256DB40D1D6D /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = PetstoreClient; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Release; + name = Debug; }; - 312A65877BADC6B9F09DBA3B46052BC0 /* Release */ = { + 294685D76AA9795895462E2CCD32108F /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 425268D5A6D1CD870A663BBE38B62B46 /* PromiseKit.xcconfig */; + baseConfigurationReference = F388A1ADD212030D9542E86628F22BD6 /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/PromiseKit/Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = PromiseKit; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; - 3F44D50290D52EC3C557274BDDAB4C7A /* Debug */ = { + 4F1AB8279A7C4737EB15C9417B058BCA /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGNING_REQUIRED = NO; COPY_PHASE_STRIP = NO; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_DEBUG=1", - "DEBUG=1", + "POD_CONFIGURATION_RELEASE=1", "$(inherited)", ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.2; - ONLY_ACTIVE_ARCH = YES; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; STRIP_INSTALLED_PRODUCT = NO; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SYMROOT = "${SRCROOT}/../build"; }; - name = Debug; + name = Release; }; - 5A07E6EE032BF56741D5477EDC0DB5F0 /* Debug */ = { + 649AB76BE3F66B45FB75AF3F33BE4DE1 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = FE7B50737921DC202987A0E4A1665B90 /* PetstoreClient.xcconfig */; + baseConfigurationReference = 451D13FDA61BDE9EB91BBC6CEA52AED4 /* PromiseKit.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PromiseKit/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = PetstoreClient; + MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; + PRODUCT_NAME = PromiseKit; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; @@ -1191,116 +1204,61 @@ }; name = Debug; }; - 5FD3C308E1FF2B6C127426676CBBBEF9 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGNING_REQUIRED = NO; - COPY_PHASE_STRIP = YES; - ENABLE_NS_ASSERTIONS = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_RELEASE=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.2; - PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; - STRIP_INSTALLED_PRODUCT = NO; - SYMROOT = "${SRCROOT}/../build"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 67FE537456A8A54A8081FE9473FB59D8 /* Debug */ = { + 6CD2CF3CB56F8D2390B8CD744515AD17 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 425268D5A6D1CD870A663BBE38B62B46 /* PromiseKit.xcconfig */; + baseConfigurationReference = 45FB2502919E80623D265FE19C0A8FC4 /* Alamofire.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/PromiseKit/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = PromiseKit; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_NAME = Alamofire; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Debug; + name = Release; }; - 8892A82330D242C8CE8BF39F1275BA41 /* Debug */ = { + 972BD31D68F98035DE59A64D32AC1F3A /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; + baseConfigurationReference = 45FB2502919E80623D265FE19C0A8FC4 /* Alamofire.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.2; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_SwaggerClient; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_NAME = Alamofire; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; @@ -1309,101 +1267,89 @@ }; name = Debug; }; - C66477B6E5656B1F4785FD5D9546905A /* Release */ = { + A202743388C540E1DF69433359FC9B9A /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */; + baseConfigurationReference = F1ED5AD8A7A28479CDC87C72B75010ED /* PetstoreClient.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.2; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_SwaggerClientTests; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + PRODUCT_NAME = PetstoreClient; SDKROOT = iphoneos; SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; - D60F8C4DE6B0D221A33959774DA3DAFF /* Debug */ = { + A93B9572FCFA5D48D91E2814712E978D /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 6C68BF2CC332C9D6485B777BA7C063AE /* Alamofire.xcconfig */; + baseConfigurationReference = 451D13FDA61BDE9EB91BBC6CEA52AED4 /* PromiseKit.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PromiseKit/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = Alamofire; + MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; + PRODUCT_NAME = PromiseKit; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Debug; + name = Release; }; - F89C2DC5B4DBA79FB9C8BA8F24E52DF4 /* Debug */ = { + E5AEBAF82849035F9A9CD1F299E57E07 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */; + baseConfigurationReference = 1ACCB3378E1513AEAADC85C4036257E4 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 9.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; @@ -1418,14 +1364,77 @@ }; name = Debug; }; + E95097900ACBDB730939D23AFE3D24CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { isa = XCConfigurationList; buildConfigurations = ( - 3F44D50290D52EC3C557274BDDAB4C7A /* Debug */, - 5FD3C308E1FF2B6C127426676CBBBEF9 /* Release */, + E95097900ACBDB730939D23AFE3D24CD /* Debug */, + 4F1AB8279A7C4737EB15C9417B058BCA /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1433,44 +1442,44 @@ 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( - D60F8C4DE6B0D221A33959774DA3DAFF /* Debug */, - 077C4BB7DBEAA715DED46C057DC8051C /* Release */, + 972BD31D68F98035DE59A64D32AC1F3A /* Debug */, + 6CD2CF3CB56F8D2390B8CD744515AD17 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 607382BCFF2B60BA932C95EC3C22A69F /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { + 4E531EDABB05EEFCF77F621FDF76EE61 /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { isa = XCConfigurationList; buildConfigurations = ( - 8892A82330D242C8CE8BF39F1275BA41 /* Debug */, - 007503D8498115ADB100193B3AD6BACC /* Release */, + 0A501A275C2C77F82FD28A347B80496E /* Debug */, + A202743388C540E1DF69433359FC9B9A /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 9EAF730020668F908855C7CE58AD558B /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + 607382BCFF2B60BA932C95EC3C22A69F /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { isa = XCConfigurationList; buildConfigurations = ( - 5A07E6EE032BF56741D5477EDC0DB5F0 /* Debug */, - 2C23BEE8A5AA6F2B41B70CC48B77C8AF /* Release */, + 1DF48E764052158CE8AC40DB7B84172C /* Debug */, + 294685D76AA9795895462E2CCD32108F /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - B462F7329881FF6565EF44016BE2B959 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */ = { + 6DABECADE21FD2D0306FD65D1962D82C /* Build configuration list for PBXNativeTarget "PromiseKit" */ = { isa = XCConfigurationList; buildConfigurations = ( - F89C2DC5B4DBA79FB9C8BA8F24E52DF4 /* Debug */, - C66477B6E5656B1F4785FD5D9546905A /* Release */, + 649AB76BE3F66B45FB75AF3F33BE4DE1 /* Debug */, + A93B9572FCFA5D48D91E2814712E978D /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - EF55B259278E6A593DF7F60BDD524C1D /* Build configuration list for PBXNativeTarget "PromiseKit" */ = { + B462F7329881FF6565EF44016BE2B959 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */ = { isa = XCConfigurationList; buildConfigurations = ( - 67FE537456A8A54A8081FE9473FB59D8 /* Debug */, - 312A65877BADC6B9F09DBA3B46052BC0 /* Release */, + E5AEBAF82849035F9A9CD1F299E57E07 /* Debug */, + 1928FD2BA1177E86A2DAF2641C8755AA /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig index 619e5f4acefe..881c8cade671 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -1,9 +1,9 @@ -CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig index 7a5671448650..983ce31eaa7f 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig @@ -1,10 +1,10 @@ -CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/PetstoreClient -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit" +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PODS_TARGET_SRCROOT = ${PODS_ROOT}/../.. PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh index 0fbbf6892e0c..d5a177d2a053 100755 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh @@ -6,10 +6,14 @@ mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") +# Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then @@ -58,12 +62,31 @@ install_framework() fi } -# Copies the dSYM of a vendored framework +# Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DWARF_DSYM_FOLDER_PATH}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DWARF_DSYM_FOLDER_PATH}" + # Copy the dSYM into a the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .framework.dSYM "$source")" + binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then + strip_invalid_archs "$binary" + fi + + if [[ $STRIP_BINARY_RETVAL == 1 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" + fi fi } @@ -85,10 +108,18 @@ code_sign_if_enabled() { # Strip invalid architectures strip_invalid_archs() { binary="$1" - # Get architectures for current file - archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + STRIP_BINARY_RETVAL=0 + return + fi stripped="" - for arch in $archs; do + for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 @@ -98,6 +129,7 @@ strip_invalid_archs() { if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi + STRIP_BINARY_RETVAL=1 } diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig index e6e847883ae2..52a643ada6e9 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig @@ -1,11 +1,11 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit/PromiseKit.framework/Headers" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient/PetstoreClient.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PetstoreClient" -framework "PromiseKit" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig index e6e847883ae2..52a643ada6e9 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig @@ -1,11 +1,11 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit/PromiseKit.framework/Headers" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient/PetstoreClient.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PetstoreClient" -framework "PromiseKit" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh index 88dd53799078..881cbaed3244 100755 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh @@ -6,10 +6,14 @@ mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") +# Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then @@ -58,12 +62,31 @@ install_framework() fi } -# Copies the dSYM of a vendored framework +# Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DWARF_DSYM_FOLDER_PATH}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DWARF_DSYM_FOLDER_PATH}" + # Copy the dSYM into a the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .framework.dSYM "$source")" + binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then + strip_invalid_archs "$binary" + fi + + if [[ $STRIP_BINARY_RETVAL == 1 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" + fi fi } @@ -85,10 +108,18 @@ code_sign_if_enabled() { # Strip invalid architectures strip_invalid_archs() { binary="$1" - # Get architectures for current file - archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + STRIP_BINARY_RETVAL=0 + return + fi stripped="" - for arch in $archs; do + for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 @@ -98,6 +129,7 @@ strip_invalid_archs() { if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi + STRIP_BINARY_RETVAL=1 } if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig index ccac9379a866..436aa2cb9edf 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig @@ -1,8 +1,8 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit/PromiseKit.framework/Headers" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient/PetstoreClient.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig index ccac9379a866..436aa2cb9edf 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig @@ -1,8 +1,8 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit/PromiseKit.framework/Headers" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PetstoreClient/PetstoreClient.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig index 657ad7b3dfbd..0e6aad60e9c7 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig @@ -1,10 +1,10 @@ -CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/PromiseKit +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" OTHER_LDFLAGS = -framework "Foundation" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PODS_TARGET_SRCROOT = ${PODS_ROOT}/PromiseKit PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift index 7151720bf4e5..05649b01abe7 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -27,14 +27,10 @@ class PetAPITests: XCTestCase { func test1CreatePet() { let expectation = self.expectation(description: "testCreatePet") - let newPet = Pet() - let category = PetstoreClient.Category() - category.id = 1234 - category.name = "eyeColor" - newPet.category = category - newPet.id = 1000 - newPet.name = "Fluffy" - newPet.status = .available + let category = PetstoreClient.Category(_id: 1234, name: "eyeColor") + let tags = [Tag(_id: 1234, name: "New York"), Tag(_id: 124321, name: "Jose")] + let newPet = Pet(_id: 1000, category: category, name: "Fluffy", photoUrls: ["https://petstore.com/sample/photo1.jpg", "https://petstore.com/sample/photo2.jpg"], tags: tags, status: .available) + PetAPI.addPet(body: newPet).then { expectation.fulfill() }.always { @@ -48,7 +44,7 @@ class PetAPITests: XCTestCase { func test2GetPet() { let expectation = self.expectation(description: "testGetPet") PetAPI.getPetById(petId: 1000).then { pet -> Void in - XCTAssert(pet.id == 1000, "invalid id") + XCTAssert(pet._id == 1000, "invalid id") XCTAssert(pet.name == "Fluffy", "invalid name") expectation.fulfill() }.always { @@ -63,6 +59,10 @@ class PetAPITests: XCTestCase { let expectation = self.expectation(description: "testDeletePet") PetAPI.deletePet(petId: 1000).then { expectation.fulfill() + }.always { + // Noop for now + }.catch { (errorType) in + XCTFail("error deleting pet") } self.waitForExpectations(timeout: testTimeout, handler: nil) } diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index b8f58649cbd0..335b79050fcf 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -18,18 +18,12 @@ class StoreAPITests: XCTestCase { let testTimeout = 10.0 func test1PlaceOrder() { - let order = Order() - let shipDate = Date() - order.id = 1000 - order.petId = 1000 - order.complete = false - order.quantity = 10 - order.shipDate = shipDate // use explicit naming to reference the enum so that we test we don't regress on enum naming - order.status = Order.Status.placed + let shipDate = Date() + let order = Order(_id: 1000, petId: 1000, quantity: 10, shipDate: shipDate, status: .placed, complete: true) let expectation = self.expectation(description: "testPlaceOrder") StoreAPI.placeOrder(body: order).then { order -> Void in - XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order._id == 1000, "invalid id") XCTAssert(order.quantity == 10, "invalid quantity") XCTAssert(order.status == .placed, "invalid status") XCTAssert(order.shipDate!.isEqual(shipDate, format: self.isoDateFormat), @@ -47,7 +41,7 @@ class StoreAPITests: XCTestCase { func test2GetOrder() { let expectation = self.expectation(description: "testGetOrder") StoreAPI.getOrderById(orderId: 1000).then { order -> Void in - XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order._id == 1000, "invalid id") XCTAssert(order.quantity == 10, "invalid quantity") XCTAssert(order.status == .placed, "invalid status") expectation.fulfill() @@ -63,6 +57,10 @@ class StoreAPITests: XCTestCase { let expectation = self.expectation(description: "testDeleteOrder") StoreAPI.deleteOrder(orderId: "1000").then { expectation.fulfill() + }.always { + // Noop for now + }.catch { (error) in + XCTFail("error deleting order") } self.waitForExpectations(timeout: testTimeout, handler: nil) } diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 3042129608c6..159c5d8ff8a7 100644 --- a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -14,11 +14,15 @@ import XCTest class UserAPITests: XCTestCase { let testTimeout = 10.0 - + func testLogin() { let expectation = self.expectation(description: "testLogin") UserAPI.loginUser(username: "swiftTester", password: "swift").then { _ -> Void in - expectation.fulfill() + expectation.fulfill() + }.always { + // Noop for now + }.catch { (error) in + XCTFail("login error") } self.waitForExpectations(timeout: testTimeout, handler: nil) } @@ -27,23 +31,23 @@ class UserAPITests: XCTestCase { let expectation = self.expectation(description: "testLogout") UserAPI.logoutUser().then { expectation.fulfill() + }.always { + // Noop for now + }.catch { (error) in + XCTFail("") } self.waitForExpectations(timeout: testTimeout, handler: nil) } func test1CreateUser() { let expectation = self.expectation(description: "testCreateUser") - let newUser = User() - newUser.email = "test@test.com" - newUser.firstName = "Test" - newUser.lastName = "Tester" - newUser.id = 1000 - newUser.password = "test!" - newUser.phone = "867-5309" - newUser.username = "test@test.com" - newUser.userStatus = 0 + let newUser = User(_id: 1000, username: "test@test.com", firstName: "Test", lastName: "Tester", email: "test@test.com", password: "test!", phone: "867-5309", userStatus: 0) UserAPI.createUser(body: newUser).then { expectation.fulfill() + }.always { + // Noop for now + }.catch { (error) in + XCTFail("create user error") } self.waitForExpectations(timeout: testTimeout, handler: nil) } @@ -51,13 +55,13 @@ class UserAPITests: XCTestCase { func test2GetUser() { let expectation = self.expectation(description: "testGetUser") UserAPI.getUserByName(username: "test@test.com").then {user -> Void in - XCTAssert(user.userStatus == 0, "invalid userStatus") - XCTAssert(user.email == "test@test.com", "invalid email") - XCTAssert(user.firstName == "Test", "invalid firstName") - XCTAssert(user.lastName == "Tester", "invalid lastName") - XCTAssert(user.password == "test!", "invalid password") - XCTAssert(user.phone == "867-5309", "invalid phone") - expectation.fulfill() + XCTAssert(user.userStatus == 0, "invalid userStatus") + XCTAssert(user.email == "test@test.com", "invalid email") + XCTAssert(user.firstName == "Test", "invalid firstName") + XCTAssert(user.lastName == "Tester", "invalid lastName") + XCTAssert(user.password == "test!", "invalid password") + XCTAssert(user.phone == "867-5309", "invalid phone") + expectation.fulfill() }.always { // Noop for now }.catch { errorType in @@ -70,6 +74,10 @@ class UserAPITests: XCTestCase { let expectation = self.expectation(description: "testDeleteUser") UserAPI.deleteUser(username: "test@test.com").then { expectation.fulfill() + }.always { + // Noop for now + }.catch { (error) in + XCTFail("deleting user error") } self.waitForExpectations(timeout: testTimeout, handler: nil) } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift index b612ff90921a..81e7286d6d40 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -6,12 +6,11 @@ import Foundation -class APIHelper { - static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { - var destination = [String:Any]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = value +public struct APIHelper { + public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + let destination = source.reduce(into: [String: Any]()) { (result, item) in + if let value = item.value { + result[item.key] = value } } @@ -21,45 +20,46 @@ class APIHelper { return destination } - static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { - var destination = [String:String]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = "\(value)" + public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + return source.reduce(into: [String: String]()) { (result, item) in + if let collection = item.value as? Array { + result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = "\(value)" } } - return destination } - static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { guard let source = source else { return nil } - var destination = [String:Any]() - let theTrue = NSNumber(value: true as Bool) - let theFalse = NSNumber(value: false as Bool) - for (key, value) in source { - switch value { - case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse: - destination[key] = "\(value as! Bool)" as Any? + + return source.reduce(into: [String: Any](), { (result, item) in + switch item.value { + case let x as Bool: + result[item.key] = x.description default: - destination[key] = value + result[item.key] = item.value } - } - return destination + }) } - static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { - let returnValues = values - .filter { $0.1 != nil } - .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in - URLQueryItem(name: item._key, value:"\(item._value!)") + public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in + if let collection = item.value as? Array { + let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + result.append(URLQueryItem(name: item.key, value: value)) + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: "\(value)")) } - if returnValues.count == 0 { + } + + if destination.isEmpty { return nil } - return returnValues + return destination } - } + diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift index 745d640ec1cf..2c2fc3157de4 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift @@ -16,10 +16,10 @@ open class PetstoreClientAPI { open class RequestBuilder { var credential: URLCredential? var headers: [String:String] - let parameters: [String:Any]? - let isBody: Bool - let method: String - let URLString: String + public let parameters: [String:Any]? + public let isBody: Bool + public let method: String + public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift index 36bb08d383ec..7ef6ef601485 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift @@ -20,7 +20,7 @@ open class AnotherFakeAPI { */ open class func testSpecialTags(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testSpecialTagsWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -61,8 +61,7 @@ open class AnotherFakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 34655eaf98be..9acfe228c6c3 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -19,7 +19,7 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerialize(body: OuterBoolean? = nil, completion: @escaping ((_ data: OuterBoolean?,_ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -56,8 +56,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -71,7 +70,7 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -112,8 +111,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -127,7 +125,7 @@ open class FakeAPI { */ open class func fakeOuterNumberSerialize(body: OuterNumber? = nil, completion: @escaping ((_ data: OuterNumber?,_ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -164,8 +162,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -179,7 +176,7 @@ open class FakeAPI { */ open class func fakeOuterStringSerialize(body: OuterString? = nil, completion: @escaping ((_ data: OuterString?,_ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -216,8 +213,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -232,7 +228,7 @@ open class FakeAPI { */ open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -273,8 +269,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -300,9 +295,13 @@ open class FakeAPI { - parameter callback: (form) None (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -327,11 +326,11 @@ open class FakeAPI { */ open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> Observable { return Observable.create { observer -> Disposable in - testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { error in + testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -386,9 +385,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -475,9 +473,13 @@ open class FakeAPI { - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -496,11 +498,11 @@ open class FakeAPI { */ open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil) -> Observable { return Observable.create { observer -> Disposable in - testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { error in + testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -535,14 +537,13 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, "enum_query_integer": enumQueryInteger?.rawValue ]) - let nillableHeaders: [String: Any?] = [ "enum_header_string_array": enumHeaderStringArray, "enum_header_string": enumHeaderString?.rawValue @@ -560,9 +561,13 @@ open class FakeAPI { - parameter param: (body) request body - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: Any, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: Any, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -574,11 +579,11 @@ open class FakeAPI { */ open class func testInlineAdditionalProperties(param: Any) -> Observable { return Observable.create { observer -> Disposable in - testInlineAdditionalProperties(param: param) { error in + testInlineAdditionalProperties(param: param) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -600,8 +605,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -615,9 +619,13 @@ open class FakeAPI { - parameter param2: (form) field2 - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -630,11 +638,11 @@ open class FakeAPI { */ open class func testJsonFormData(param: String, param2: String) -> Observable { return Observable.create { observer -> Disposable in - testJsonFormData(param: param, param2: param2) { error in + testJsonFormData(param: param, param2: param2) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -662,9 +670,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift index 6410bb42141c..30cd8561e287 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeClassnameTags123API.swift @@ -20,7 +20,7 @@ open class FakeClassnameTags123API { */ open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -47,6 +47,7 @@ open class FakeClassnameTags123API { /** To test class name in snake case - PATCH /fake_classname_test + - To test class name in snake case - API Key: - type: apiKey api_key_query (QUERY) - name: api_key_query @@ -63,8 +64,7 @@ open class FakeClassnameTags123API { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift deleted file mode 100644 index 7d795543bfbd..000000000000 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift +++ /dev/null @@ -1,74 +0,0 @@ -// -// Fake_classname_tags123API.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation -import Alamofire -import RxSwift - - - -open class Fake_classname_tags123API { - /** - To test class name in snake case - - - parameter body: (body) client model - - parameter completion: completion handler to receive the data and the error objects - */ - open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { - testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); - } - } - - /** - To test class name in snake case - - - parameter body: (body) client model - - returns: Observable - */ - open class func testClassname(body: Client) -> Observable { - return Observable.create { observer -> Disposable in - testClassname(body: body) { data, error in - if let error = error { - observer.on(.error(error)) - } else { - observer.on(.next(data!)) - } - observer.on(.completed) - } - return Disposables.create() - } - } - - /** - To test class name in snake case - - PATCH /fake_classname_test - - API Key: - - type: apiKey api_key_query (QUERY) - - name: api_key_query - - examples: [{contentType=application/json, example={ - "client" : "client" -}}] - - - parameter body: (body) client model - - - returns: RequestBuilder - */ - open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - - let url = NSURLComponents(string: URLString) - - - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) - } - -} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index c58387ec65fa..e2c34075e245 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -18,9 +18,13 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + open class func addPet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -32,11 +36,11 @@ open class PetAPI { */ open class func addPet(body: Pet) -> Observable { return Observable.create { observer -> Disposable in - addPet(body: body) { error in + addPet(body: body) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -61,8 +65,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -76,9 +79,13 @@ open class PetAPI { - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -91,11 +98,11 @@ open class PetAPI { */ open class func deletePet(petId: Int64, apiKey: String? = nil) -> Observable { return Observable.create { observer -> Disposable in - deletePet(petId: petId, apiKey: apiKey) { error in + deletePet(petId: petId, apiKey: apiKey) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -118,12 +125,13 @@ open class PetAPI { */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey ] @@ -151,7 +159,7 @@ open class PetAPI { */ open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -275,12 +283,11 @@ open class PetAPI { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status ]) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -295,7 +302,7 @@ open class PetAPI { */ open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -419,12 +426,11 @@ open class PetAPI { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags ]) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -439,7 +445,7 @@ open class PetAPI { */ open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -529,12 +535,13 @@ open class PetAPI { */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -547,9 +554,13 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -561,11 +572,11 @@ open class PetAPI { */ open class func updatePet(body: Pet) -> Observable { return Observable.create { observer -> Disposable in - updatePet(body: body) { error in + updatePet(body: body) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -590,8 +601,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -606,9 +616,13 @@ open class PetAPI { - parameter status: (form) Updated status of the pet (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -622,11 +636,11 @@ open class PetAPI { */ open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil) -> Observable { return Observable.create { observer -> Disposable in - updatePetWithForm(petId: petId, name: name, status: status) { error in + updatePetWithForm(petId: petId, name: name, status: status) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -650,7 +664,9 @@ open class PetAPI { */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "name": name, @@ -659,9 +675,8 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -678,7 +693,7 @@ open class PetAPI { */ open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -725,7 +740,9 @@ open class PetAPI { */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { var path = "/pet/{petId}/uploadImage" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "additionalMetadata": additionalMetadata, @@ -734,9 +751,8 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 5fa6d69ff073..6aa649869ff8 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -18,9 +18,13 @@ open class StoreAPI { - parameter orderId: (path) ID of the order that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -32,11 +36,11 @@ open class StoreAPI { */ open class func deleteOrder(orderId: String) -> Observable { return Observable.create { observer -> Disposable in - deleteOrder(orderId: orderId) { error in + deleteOrder(orderId: orderId) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -55,12 +59,13 @@ open class StoreAPI { */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -74,7 +79,7 @@ open class StoreAPI { */ open class func getInventory(completion: @escaping ((_ data: [String:Int]?,_ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -114,9 +119,8 @@ open class StoreAPI { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -131,7 +135,7 @@ open class StoreAPI { */ open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -196,12 +200,13 @@ open class StoreAPI { */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -216,7 +221,7 @@ open class StoreAPI { */ open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -284,8 +289,7 @@ open class StoreAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 34df08eec8d0..f70a08796b64 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -18,9 +18,13 @@ open class UserAPI { - parameter body: (body) Created user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUser(body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -32,11 +36,11 @@ open class UserAPI { */ open class func createUser(body: User) -> Observable { return Observable.create { observer -> Disposable in - createUser(body: body) { error in + createUser(body: body) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -58,8 +62,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -72,9 +75,13 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -86,11 +93,11 @@ open class UserAPI { */ open class func createUsersWithArrayInput(body: [User]) -> Observable { return Observable.create { observer -> Disposable in - createUsersWithArrayInput(body: body) { error in + createUsersWithArrayInput(body: body) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -112,8 +119,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -126,9 +132,13 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -140,11 +150,11 @@ open class UserAPI { */ open class func createUsersWithListInput(body: [User]) -> Observable { return Observable.create { observer -> Disposable in - createUsersWithListInput(body: body) { error in + createUsersWithListInput(body: body) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -166,8 +176,7 @@ open class UserAPI { let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -180,9 +189,13 @@ open class UserAPI { - parameter username: (path) The name that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, completion: @escaping ((_ error: Error?) -> Void)) { + open class func deleteUser(username: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -194,11 +207,11 @@ open class UserAPI { */ open class func deleteUser(username: String) -> Observable { return Observable.create { observer -> Disposable in - deleteUser(username: username) { error in + deleteUser(username: username) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -217,12 +230,13 @@ open class UserAPI { */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -232,19 +246,19 @@ open class UserAPI { /** Get user by user name - - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter completion: completion handler to receive the data and the error objects */ open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } /** Get user by user name - - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - returns: Observable */ open class func getUserByName(username: String) -> Observable { @@ -304,18 +318,19 @@ open class UserAPI { "username" : "username" }}] - - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -331,7 +346,7 @@ open class UserAPI { */ open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -374,13 +389,12 @@ open class UserAPI { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username, "password": password ]) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -392,9 +406,13 @@ open class UserAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(completion: @escaping ((_ error: Error?) -> Void)) { + open class func logoutUser(completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -405,11 +423,11 @@ open class UserAPI { */ open class func logoutUser() -> Observable { return Observable.create { observer -> Disposable in - logoutUser() { error in + logoutUser() { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -428,9 +446,8 @@ open class UserAPI { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - + + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -444,9 +461,13 @@ open class UserAPI { - parameter body: (body) Updated user object - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, completion: @escaping ((_ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in - completion(error); + if error == nil { + completion((), error) + } else { + completion(nil, error) + } } } @@ -459,11 +480,11 @@ open class UserAPI { */ open class func updateUser(username: String, body: User) -> Observable { return Observable.create { observer -> Disposable in - updateUser(username: username, body: body) { error in + updateUser(username: username, body: body) { data, error in if let error = error { observer.on(.error(error)) } else { - observer.on(.next(())) + observer.on(.next(data!)) } observer.on(.completed) } @@ -483,12 +504,13 @@ open class UserAPI { */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = NSURLComponents(string: URLString) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 24351523736d..381fddcc81fb 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -268,7 +268,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift index 4cf4ac206af5..19ee06b1f487 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift @@ -24,4 +24,20 @@ open class JSONEncodingHelper { return params } + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { + var params: Parameters? = nil + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error) + return nil + } + } + + return params + } + } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift index 8388bfb035fc..6c1e6653b6f9 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift @@ -14,6 +14,10 @@ public struct AdditionalPropertiesClass: Codable { public var mapProperty: [String:String]? public var mapOfMapProperty: [String:[String:String]]? + public init(mapProperty: [String:String]?, mapOfMapProperty: [String:[String:String]]?) { + self.mapProperty = mapProperty + self.mapOfMapProperty = mapOfMapProperty + } public enum CodingKeys: String, CodingKey { case mapProperty = "map_property" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Animal.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Animal.swift index fa13d5e9b9f6..ba2da30fedde 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Animal.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Animal.swift @@ -14,6 +14,10 @@ public struct Animal: Codable { public var className: String public var color: String? + public init(className: String, color: String?) { + self.className = className + self.color = color + } } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift index a4e416b79a85..3fd872dcd26f 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift @@ -15,6 +15,11 @@ public struct ApiResponse: Codable { public var type: String? public var message: String? + public init(code: Int?, type: String?, message: String?) { + self.code = code + self.type = type + self.message = message + } } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift index 8aea70bfc69b..ac59328a279f 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift @@ -13,6 +13,9 @@ public struct ArrayOfArrayOfNumberOnly: Codable { public var arrayArrayNumber: [[Double]]? + public init(arrayArrayNumber: [[Double]]?) { + self.arrayArrayNumber = arrayArrayNumber + } public enum CodingKeys: String, CodingKey { case arrayArrayNumber = "ArrayArrayNumber" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift index c670c41c217e..1132638458fc 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift @@ -13,6 +13,9 @@ public struct ArrayOfNumberOnly: Codable { public var arrayNumber: [Double]? + public init(arrayNumber: [Double]?) { + self.arrayNumber = arrayNumber + } public enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift index 6257fb4cc9bb..14335a750539 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift @@ -15,6 +15,11 @@ public struct ArrayTest: Codable { public var arrayArrayOfInteger: [[Int64]]? public var arrayArrayOfModel: [[ReadOnlyFirst]]? + public init(arrayOfString: [String]?, arrayArrayOfInteger: [[Int64]]?, arrayArrayOfModel: [[ReadOnlyFirst]]?) { + self.arrayOfString = arrayOfString + self.arrayArrayOfInteger = arrayArrayOfInteger + self.arrayArrayOfModel = arrayArrayOfModel + } public enum CodingKeys: String, CodingKey { case arrayOfString = "array_of_string" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift index 952c337fa740..71ba400a9d7b 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -19,6 +19,14 @@ public struct Capitalization: Codable { /** Name of the pet */ public var ATT_NAME: String? + public init(smallCamel: String?, capitalCamel: String?, smallSnake: String?, capitalSnake: String?, sCAETHFlowPoints: String?, ATT_NAME: String?) { + self.smallCamel = smallCamel + self.capitalCamel = capitalCamel + self.smallSnake = smallSnake + self.capitalSnake = capitalSnake + self.sCAETHFlowPoints = sCAETHFlowPoints + self.ATT_NAME = ATT_NAME + } public enum CodingKeys: String, CodingKey { case smallCamel diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Cat.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Cat.swift index e9e061b5e364..7687f52d477a 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Cat.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Cat.swift @@ -15,6 +15,11 @@ public struct Cat: Codable { public var color: String? public var declawed: Bool? + public init(className: String, color: String?, declawed: Bool?) { + self.className = className + self.color = color + self.declawed = declawed + } } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift index 2975a53a5079..fa0786832c63 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -14,6 +14,10 @@ public struct Category: Codable { public var _id: Int64? public var name: String? + public init(_id: Int64?, name: String?) { + self._id = _id + self.name = name + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift index 90da5c2cf4dc..3a38128215a2 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift @@ -14,6 +14,9 @@ public struct ClassModel: Codable { public var _class: String? + public init(_class: String?) { + self._class = _class + } } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Client.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Client.swift index f4333883e631..0c4fc0d559a9 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Client.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Client.swift @@ -13,6 +13,9 @@ public struct Client: Codable { public var client: String? + public init(client: String?) { + self.client = client + } } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Dog.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Dog.swift index b86c61c0ee34..9ba84f7f8cc5 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Dog.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Dog.swift @@ -15,6 +15,11 @@ public struct Dog: Codable { public var color: String? public var breed: String? + public init(className: String, color: String?, breed: String?) { + self.className = className + self.color = color + self.breed = breed + } } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift index 145acd9dd347..084a9ab83836 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift @@ -22,6 +22,10 @@ public struct EnumArrays: Codable { public var justSymbol: JustSymbol? public var arrayEnum: [ArrayEnum]? + public init(justSymbol: JustSymbol?, arrayEnum: [ArrayEnum]?) { + self.justSymbol = justSymbol + self.arrayEnum = arrayEnum + } public enum CodingKeys: String, CodingKey { case justSymbol = "just_symbol" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index 74b693c7bb61..6374df494a32 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -16,6 +16,11 @@ public struct EnumTest: Codable { case lower = "lower" case empty = "" } + public enum EnumStringRequired: String, Codable { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } public enum EnumInteger: Int, Codable { case _1 = 1 case number1 = -1 @@ -25,13 +30,22 @@ public struct EnumTest: Codable { case number12 = -1.2 } public var enumString: EnumString? + public var enumStringRequired: EnumStringRequired public var enumInteger: EnumInteger? public var enumNumber: EnumNumber? public var outerEnum: OuterEnum? + public init(enumString: EnumString?, enumStringRequired: EnumStringRequired, enumInteger: EnumInteger?, enumNumber: EnumNumber?, outerEnum: OuterEnum?) { + self.enumString = enumString + self.enumStringRequired = enumStringRequired + self.enumInteger = enumInteger + self.enumNumber = enumNumber + self.outerEnum = outerEnum + } public enum CodingKeys: String, CodingKey { case enumString = "enum_string" + case enumStringRequired = "enum_string_required" case enumInteger = "enum_integer" case enumNumber = "enum_number" case outerEnum diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift index 0ce1edc16b07..1fc4bd362fd1 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift @@ -25,6 +25,21 @@ public struct FormatTest: Codable { public var uuid: UUID? public var password: String + public init(integer: Int?, int32: Int?, int64: Int64?, number: Double, float: Float?, double: Double?, string: String?, byte: Data, binary: Data?, date: Date, dateTime: Date?, uuid: UUID?, password: String) { + self.integer = integer + self.int32 = int32 + self.int64 = int64 + self.number = number + self.float = float + self.double = double + self.string = string + self.byte = byte + self.binary = binary + self.date = date + self.dateTime = dateTime + self.uuid = uuid + self.password = password + } } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift index 23f5e679faf3..3626846919f5 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift @@ -14,6 +14,10 @@ public struct HasOnlyReadOnly: Codable { public var bar: String? public var foo: String? + public init(bar: String?, foo: String?) { + self.bar = bar + self.foo = foo + } } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/List.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/List.swift index 382702867a89..fe11bfce8402 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/List.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/List.swift @@ -13,6 +13,9 @@ public struct List: Codable { public var _123List: String? + public init(_123List: String?) { + self._123List = _123List + } public enum CodingKeys: String, CodingKey { case _123List = "123-list" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MapTest.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MapTest.swift index e8f11504de5d..ded3f7b1dde1 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MapTest.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MapTest.swift @@ -18,6 +18,10 @@ public struct MapTest: Codable { public var mapMapOfString: [String:[String:String]]? public var mapOfEnumString: [String:String]? + public init(mapMapOfString: [String:[String:String]]?, mapOfEnumString: [String:String]?) { + self.mapMapOfString = mapMapOfString + self.mapOfEnumString = mapOfEnumString + } public enum CodingKeys: String, CodingKey { case mapMapOfString = "map_map_of_string" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 554c81317eb4..962b7fe65bc5 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -15,6 +15,11 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { public var dateTime: Date? public var map: [String:Animal]? + public init(uuid: UUID?, dateTime: Date?, map: [String:Animal]?) { + self.uuid = uuid + self.dateTime = dateTime + self.map = map + } } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift index 573cb42acfd4..f539cd888ab5 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift @@ -15,6 +15,10 @@ public struct Model200Response: Codable { public var name: Int? public var _class: String? + public init(name: Int?, _class: String?) { + self.name = name + self._class = _class + } public enum CodingKeys: String, CodingKey { case name diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Name.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Name.swift index b4686c2c8a4c..ddd2b9098519 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Name.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Name.swift @@ -17,6 +17,12 @@ public struct Name: Codable { public var property: String? public var _123Number: Int? + public init(name: Int, snakeCase: Int?, property: String?, _123Number: Int?) { + self.name = name + self.snakeCase = snakeCase + self.property = property + self._123Number = _123Number + } public enum CodingKeys: String, CodingKey { case name diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift index 78bb76f9bfd6..06db22e9c3ab 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift @@ -13,6 +13,9 @@ public struct NumberOnly: Codable { public var justNumber: Double? + public init(justNumber: Double?) { + self.justNumber = justNumber + } public enum CodingKeys: String, CodingKey { case justNumber = "JustNumber" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift index 26de6d8313dc..b6c0cc0cb5a2 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -24,6 +24,14 @@ public struct Order: Codable { public var status: Status? public var complete: Bool? + public init(_id: Int64?, petId: Int64?, quantity: Int?, shipDate: Date?, status: Status?, complete: Bool?) { + self._id = _id + self.petId = petId + self.quantity = quantity + self.shipDate = shipDate + self.status = status + self.complete = complete + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift index 0c77ca23f503..bd1984e870db 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift @@ -15,6 +15,11 @@ public struct OuterComposite: Codable { public var myString: OuterString? public var myBoolean: OuterBoolean? + public init(myNumber: OuterNumber?, myString: OuterString?, myBoolean: OuterBoolean?) { + self.myNumber = myNumber + self.myString = myString + self.myBoolean = myBoolean + } public enum CodingKeys: String, CodingKey { case myNumber = "my_number" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift index dcb32870f70a..73985167c966 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -24,6 +24,14 @@ public struct Pet: Codable { /** pet status in the store */ public var status: Status? + public init(_id: Int64?, category: Category?, name: String, photoUrls: [String], tags: [Tag]?, status: Status?) { + self._id = _id + self.category = category + self.name = name + self.photoUrls = photoUrls + self.tags = tags + self.status = status + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift index 7cec5cb2f927..6e984760cd6c 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift @@ -14,6 +14,10 @@ public struct ReadOnlyFirst: Codable { public var bar: String? public var baz: String? + public init(bar: String?, baz: String?) { + self.bar = bar + self.baz = baz + } } diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Return.swift index 86c3f0d8097f..9502f08130c1 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Return.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Return.swift @@ -14,6 +14,9 @@ public struct Return: Codable { public var _return: Int? + public init(_return: Int?) { + self._return = _return + } public enum CodingKeys: String, CodingKey { case _return = "return" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift index f0c0aec53944..f94741a854a3 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift @@ -13,6 +13,9 @@ public struct SpecialModelName: Codable { public var specialPropertyName: Int64? + public init(specialPropertyName: Int64?) { + self.specialPropertyName = specialPropertyName + } public enum CodingKeys: String, CodingKey { case specialPropertyName = "$special[property.name]" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift index 86c19a254d14..7dd17159a739 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -14,6 +14,10 @@ public struct Tag: Codable { public var _id: Int64? public var name: String? + public init(_id: Int64?, name: String?) { + self._id = _id + self.name = name + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift index ab73f62883e5..09b68da4f8f4 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -21,6 +21,16 @@ public struct User: Codable { /** User Status */ public var userStatus: Int? + public init(_id: Int64?, username: String?, firstName: String?, lastName: String?, email: String?, password: String?, phone: String?, userStatus: Int?) { + self._id = _id + self.username = username + self.firstName = firstName + self.lastName = lastName + self.email = email + self.password = password + self.phone = phone + self.userStatus = userStatus + } public enum CodingKeys: String, CodingKey { case _id = "id" diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 4b449325dd62..6f2f338f55cc 100644 --- a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -9,6 +9,7 @@ /* Begin PBXBuildFile section */ B024164FBFF71BF644D4419A /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */; }; B1D0246C8960F47A60098F37 /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */; }; + B596E4BD205657A500B46F03 /* APIHelperTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B596E4BC205657A500B46F03 /* APIHelperTests.swift */; }; EAEC0BC21D4E30CE00C908A3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAEC0BC11D4E30CE00C908A3 /* AppDelegate.swift */; }; EAEC0BC41D4E30CE00C908A3 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAEC0BC31D4E30CE00C908A3 /* ViewController.swift */; }; EAEC0BC71D4E30CE00C908A3 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = EAEC0BC51D4E30CE00C908A3 /* Main.storyboard */; }; @@ -35,6 +36,7 @@ 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + B596E4BC205657A500B46F03 /* APIHelperTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIHelperTests.swift; sourceTree = ""; }; EAEC0BBE1D4E30CE00C908A3 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; EAEC0BC11D4E30CE00C908A3 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; EAEC0BC31D4E30CE00C908A3 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; @@ -130,6 +132,7 @@ EAEC0BE31D4E330700C908A3 /* PetAPITests.swift */, EAEC0BE51D4E379000C908A3 /* StoreAPITests.swift */, EAEC0BE71D4E38CB00C908A3 /* UserAPITests.swift */, + B596E4BC205657A500B46F03 /* APIHelperTests.swift */, ); path = SwaggerClientTests; sourceTree = ""; @@ -358,6 +361,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + B596E4BD205657A500B46F03 /* APIHelperTests.swift in Sources */, EAEC0BE81D4E38CB00C908A3 /* UserAPITests.swift in Sources */, EAEC0BE61D4E379000C908A3 /* StoreAPITests.swift in Sources */, EAEC0BE41D4E330700C908A3 /* PetAPITests.swift in Sources */, diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/APIHelperTests.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/APIHelperTests.swift new file mode 100644 index 000000000000..3ce5e5f08454 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/APIHelperTests.swift @@ -0,0 +1,55 @@ +// +// APIHelperTests.swift +// SwaggerClientTests +// +// Created by Daiki Matsudate on 2018/03/12. +// Copyright © 2018 Swagger. All rights reserved. +// + +import XCTest +import PetstoreClient +@testable import SwaggerClient + +class APIHelperTests: XCTestCase { + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testRejectNil() { + let source: [String: Any?] = ["a": 1, "b": nil, "c": ["1", nil, "2"], "d": true, "e": false] + let expected: [String: Any] = ["a": 1, "c": ["1", nil, "2"], "d": true, "e": false] + let actual: [String: Any] = APIHelper.rejectNil(source)! + XCTAssert(NSDictionary(dictionary: actual).isEqual(to: expected)) + } + + func testRejectNilHeaders() { + let source: [String: Any?] = ["a": 1, "b": nil, "c": ["1", nil, "2"], "d": true, "e": false] + let expected: [String: String] = ["a": "1", "c": "1,2", "d": "true", "e": "false"] + let actual: [String: String] = APIHelper.rejectNilHeaders(source) + XCTAssert(NSDictionary(dictionary: actual).isEqual(to: expected)) + } + + func testConvertBoolToString() { + let source: [String: Any] = ["a": 1, "c": ["1", nil, "2"], "d": true, "e": false] + let expected: [String: Any] = ["a": 1, "c": ["1", nil, "2"], "d": "true", "e": "false"] + let actual: [String: Any] = APIHelper.convertBoolToString(source)! + XCTAssert(NSDictionary(dictionary: actual).isEqual(to: expected)) + } + + func testMapValuesToQueryItems() { + let source: [String: Any] = ["a": 1, "c": ["1", nil, "2"], "d": true, "e": false] + let expected: [URLQueryItem] = [URLQueryItem(name: "a", value: "1"), + URLQueryItem(name: "c", value: "1,2"), + URLQueryItem(name: "d", value: "true"), + URLQueryItem(name: "e", value: "false")].sorted(by: { $0.0.name > $0.1.name }) + let actual: [URLQueryItem] = APIHelper.mapValuesToQueryItems(source)!.sorted(by: { $0.0.name > $0.1.name }) + XCTAssert(actual == expected) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift index 99f4e85eac7a..eaabe70dcfb5 100644 --- a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -28,9 +28,9 @@ class PetAPITests: XCTestCase { func test1CreatePet() { let expectation = self.expectation(description: "testCreatePet") - let category = PetstoreClient.Category(id: 1234, name: "eyeColor") - let tags = [Tag(id: 1234, name: "New York"), Tag(id: 124321, name: "Jose")] - let newPet = Pet(id: 1000, category: category, name: "Fluffy", photoUrls: ["https://petstore.com/sample/photo1.jpg", "https://petstore.com/sample/photo2.jpg"], tags: tags, status: .available) + let category = PetstoreClient.Category(_id: 1234, name: "eyeColor") + let tags = [Tag(_id: 1234, name: "New York"), Tag(_id: 124321, name: "Jose")] + let newPet = Pet(_id: 1000, category: category, name: "Fluffy", photoUrls: ["https://petstore.com/sample/photo1.jpg", "https://petstore.com/sample/photo2.jpg"], tags: tags, status: .available) PetAPI.addPet(body: newPet).subscribe(onNext: { expectation.fulfill() @@ -43,17 +43,17 @@ class PetAPITests: XCTestCase { func test2GetPet() { let expectation = self.expectation(description: "testGetPet") PetAPI.getPetById(petId: 1000).subscribe(onNext: { pet in - XCTAssert(pet.id == 1000, "invalid id") + XCTAssert(pet._id == 1000, "invalid id") XCTAssert(pet.name == "Fluffy", "invalid name") - XCTAssert(pet.category!.id == 1234, "invalid category id") + XCTAssert(pet.category!._id == 1234, "invalid category id") XCTAssert(pet.category!.name == "eyeColor", "invalid category name") let tag1 = pet.tags![0] - XCTAssert(tag1.id == 1234, "invalid tag id") + XCTAssert(tag1._id == 1234, "invalid tag id") XCTAssert(tag1.name == "New York", "invalid tag name") let tag2 = pet.tags![1] - XCTAssert(tag2.id == 124321, "invalid tag id") + XCTAssert(tag2._id == 124321, "invalid tag id") XCTAssert(tag2.name == "Jose", "invalid tag name") XCTAssert(pet.photoUrls[0] == "https://petstore.com/sample/photo1.jpg") diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index 97db90b22633..81497f5e0b94 100644 --- a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -21,10 +21,10 @@ class StoreAPITests: XCTestCase { func test1PlaceOrder() { // use explicit naming to reference the enum so that we test we don't regress on enum naming let shipDate = Date() - let order = Order(id: 1000, petId: 1000, quantity: 10, shipDate: shipDate, status: .placed, complete: true) + let order = Order(_id: 1000, petId: 1000, quantity: 10, shipDate: shipDate, status: .placed, complete: true) let expectation = self.expectation(description: "testPlaceOrder") StoreAPI.placeOrder(body: order).subscribe(onNext: { order in - XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order._id == 1000, "invalid id") XCTAssert(order.quantity == 10, "invalid quantity") XCTAssert(order.status == .placed, "invalid status") XCTAssert(order.shipDate!.isEqual(shipDate, format: self.isoDateFormat), @@ -41,7 +41,7 @@ class StoreAPITests: XCTestCase { func test2GetOrder() { let expectation = self.expectation(description: "testGetOrder") StoreAPI.getOrderById(orderId: 1000).subscribe(onNext: { order -> Void in - XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order._id == 1000, "invalid id") XCTAssert(order.quantity == 10, "invalid quantity") XCTAssert(order.status == .placed, "invalid status") XCTAssert(order.complete == true, "invalid complete") diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index fbe9c68db3a7..d18372e27be1 100644 --- a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -67,7 +67,7 @@ class UserAPITests: XCTestCase { func test1CreateUser() { let expectation = self.expectation(description: "testCreateUser") - let newUser = User(id: 1000, username: "test@test.com", firstName: "Test", lastName: "Tester", email: "test@test.com", password: "test!", phone: "867-5309", userStatus: 0) + let newUser = User(_id: 1000, username: "test@test.com", firstName: "Test", lastName: "Tester", email: "test@test.com", password: "test!", phone: "867-5309", userStatus: 0) UserAPI.createUser(body: newUser).subscribe(onNext: { expectation.fulfill() }, onError: { errorType in diff --git a/samples/client/petstore/tizen/.swagger-codegen/VERSION b/samples/client/petstore/tizen/.swagger-codegen/VERSION index f9f7450d1359..096bf47efe31 100644 --- a/samples/client/petstore/tizen/.swagger-codegen/VERSION +++ b/samples/client/petstore/tizen/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/tizen/src/ApiResponse.cpp b/samples/client/petstore/tizen/src/ApiResponse.cpp index bf5974f717cf..cf0280d7bfd0 100644 --- a/samples/client/petstore/tizen/src/ApiResponse.cpp +++ b/samples/client/petstore/tizen/src/ApiResponse.cpp @@ -23,16 +23,9 @@ ApiResponse::~ApiResponse() void ApiResponse::__init() { - // - // //code = int(0); - // - // //type = std::string(); - // - // //message = std::string(); - // } void diff --git a/samples/client/petstore/tizen/src/Category.cpp b/samples/client/petstore/tizen/src/Category.cpp index 85262d29f14b..1d60699c1c0b 100644 --- a/samples/client/petstore/tizen/src/Category.cpp +++ b/samples/client/petstore/tizen/src/Category.cpp @@ -23,13 +23,8 @@ Category::~Category() void Category::__init() { - // - // //id = long(0); - // - // //name = std::string(); - // } void diff --git a/samples/client/petstore/tizen/src/Order.cpp b/samples/client/petstore/tizen/src/Order.cpp index f3e3a201d6b3..e9000fdf12c2 100644 --- a/samples/client/petstore/tizen/src/Order.cpp +++ b/samples/client/petstore/tizen/src/Order.cpp @@ -23,25 +23,12 @@ Order::~Order() void Order::__init() { - // - // //id = long(0); - // - // //petId = long(0); - // - // //quantity = int(0); - // - // //shipDate = null; - // - // //status = std::string(); - // - // //complete = bool(false); - // } void diff --git a/samples/client/petstore/tizen/src/Pet.cpp b/samples/client/petstore/tizen/src/Pet.cpp index 74f95f151ec7..8632c5bb01d2 100644 --- a/samples/client/petstore/tizen/src/Pet.cpp +++ b/samples/client/petstore/tizen/src/Pet.cpp @@ -23,25 +23,12 @@ Pet::~Pet() void Pet::__init() { - // - // //id = long(0); - // - // //category = new Category(); - // - // //name = std::string(); - // //new std::list()std::list> photoUrls; - // - // //new std::list()std::list> tags; - // - // - // //status = std::string(); - // } void diff --git a/samples/client/petstore/tizen/src/PetManager.cpp b/samples/client/petstore/tizen/src/PetManager.cpp index 2f273a21e10d..32357704d6e4 100644 --- a/samples/client/petstore/tizen/src/PetManager.cpp +++ b/samples/client/petstore/tizen/src/PetManager.cpp @@ -82,7 +82,7 @@ static bool addPetProcessor(MemoryStruct_s p_chunk, long code, char* errormsg, v } static bool addPetHelper(char * accessToken, - Pet body, + Pet pet, void(* handler)(Error, void* ) , void* userData, bool isAsync) { @@ -105,10 +105,10 @@ static bool addPetHelper(char * accessToken, JsonArray* json_array; if (isprimitive("Pet")) { - node = converttoJson(&body, "Pet", ""); + node = converttoJson(&pet, "Pet", ""); } - char *jsonStr = body.toJson(); + char *jsonStr = pet.toJson(); node = json_from_string(jsonStr, NULL); g_free(static_cast(jsonStr)); @@ -167,22 +167,22 @@ static bool addPetHelper(char * accessToken, bool PetManager::addPetAsync(char * accessToken, - Pet body, + Pet pet, void(* handler)(Error, void* ) , void* userData) { return addPetHelper(accessToken, - body, + pet, handler, userData, true); } bool PetManager::addPetSync(char * accessToken, - Pet body, + Pet pet, void(* handler)(Error, void* ) , void* userData) { return addPetHelper(accessToken, - body, + pet, handler, userData, false); } @@ -387,12 +387,10 @@ static bool findPetsByStatusHelper(char * accessToken, map queryParams; string itemAtq; - for (std::list - ::iterator queryIter = status.begin(); queryIter != status.end(); ++queryIter) { - string itemAt = stringify(&(*queryIter), "std::string"); - queryParams.insert(pair("status", itemAt)); - } - + + itemAtq = stringify(&status, "std::list"); + queryParams.insert(pair("status", itemAtq)); + string mBody = ""; JsonNode* node; JsonArray* json_array; @@ -531,12 +529,10 @@ static bool findPetsByTagsHelper(char * accessToken, map queryParams; string itemAtq; - for (std::list - ::iterator queryIter = tags.begin(); queryIter != tags.end(); ++queryIter) { - string itemAt = stringify(&(*queryIter), "std::string"); - queryParams.insert(pair("tags", itemAt)); - } - + + itemAtq = stringify(&tags, "std::list"); + queryParams.insert(pair("tags", itemAtq)); + string mBody = ""; JsonNode* node; JsonArray* json_array; @@ -796,7 +792,7 @@ static bool updatePetProcessor(MemoryStruct_s p_chunk, long code, char* errormsg } static bool updatePetHelper(char * accessToken, - Pet body, + Pet pet, void(* handler)(Error, void* ) , void* userData, bool isAsync) { @@ -819,10 +815,10 @@ static bool updatePetHelper(char * accessToken, JsonArray* json_array; if (isprimitive("Pet")) { - node = converttoJson(&body, "Pet", ""); + node = converttoJson(&pet, "Pet", ""); } - char *jsonStr = body.toJson(); + char *jsonStr = pet.toJson(); node = json_from_string(jsonStr, NULL); g_free(static_cast(jsonStr)); @@ -881,22 +877,22 @@ static bool updatePetHelper(char * accessToken, bool PetManager::updatePetAsync(char * accessToken, - Pet body, + Pet pet, void(* handler)(Error, void* ) , void* userData) { return updatePetHelper(accessToken, - body, + pet, handler, userData, true); } bool PetManager::updatePetSync(char * accessToken, - Pet body, + Pet pet, void(* handler)(Error, void* ) , void* userData) { return updatePetHelper(accessToken, - body, + pet, handler, userData, false); } diff --git a/samples/client/petstore/tizen/src/PetManager.h b/samples/client/petstore/tizen/src/PetManager.h index 93f095441200..e3ab9a775b17 100644 --- a/samples/client/petstore/tizen/src/PetManager.h +++ b/samples/client/petstore/tizen/src/PetManager.h @@ -28,26 +28,26 @@ class PetManager { /*! \brief Add a new pet to the store. *Synchronous* * * - * \param body Pet object that needs to be added to the store *Required* + * \param pet Pet object that needs to be added to the store *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool addPetSync(char * accessToken, - Pet body, + Pet pet, void(* handler)(Error, void* ) , void* userData); /*! \brief Add a new pet to the store. *Asynchronous* * * - * \param body Pet object that needs to be added to the store *Required* + * \param pet Pet object that needs to be added to the store *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool addPetAsync(char * accessToken, - Pet body, + Pet pet, void(* handler)(Error, void* ) , void* userData); @@ -165,26 +165,26 @@ bool getPetByIdAsync(char * accessToken, /*! \brief Update an existing pet. *Synchronous* * * - * \param body Pet object that needs to be added to the store *Required* + * \param pet Pet object that needs to be added to the store *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool updatePetSync(char * accessToken, - Pet body, + Pet pet, void(* handler)(Error, void* ) , void* userData); /*! \brief Update an existing pet. *Asynchronous* * * - * \param body Pet object that needs to be added to the store *Required* + * \param pet Pet object that needs to be added to the store *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool updatePetAsync(char * accessToken, - Pet body, + Pet pet, void(* handler)(Error, void* ) , void* userData); diff --git a/samples/client/petstore/tizen/src/StoreManager.cpp b/samples/client/petstore/tizen/src/StoreManager.cpp index e107ff844349..475d4357f901 100644 --- a/samples/client/petstore/tizen/src/StoreManager.cpp +++ b/samples/client/petstore/tizen/src/StoreManager.cpp @@ -510,7 +510,7 @@ static bool placeOrderProcessor(MemoryStruct_s p_chunk, long code, char* errorms } static bool placeOrderHelper(char * accessToken, - Order body, + Order order, void(* handler)(Order, Error, void* ) , void* userData, bool isAsync) { @@ -522,7 +522,7 @@ static bool placeOrderHelper(char * accessToken, string accessHeader = "Authorization: Bearer "; accessHeader.append(accessToken); headerList = curl_slist_append(headerList, accessHeader.c_str()); - headerList = curl_slist_append(headerList, "Content-Type: application/json"); + headerList = curl_slist_append(headerList, "Content-Type: */*"); map queryParams; string itemAtq; @@ -532,10 +532,10 @@ static bool placeOrderHelper(char * accessToken, JsonArray* json_array; if (isprimitive("Order")) { - node = converttoJson(&body, "Order", ""); + node = converttoJson(&order, "Order", ""); } - char *jsonStr = body.toJson(); + char *jsonStr = order.toJson(); node = json_from_string(jsonStr, NULL); g_free(static_cast(jsonStr)); @@ -594,22 +594,22 @@ static bool placeOrderHelper(char * accessToken, bool StoreManager::placeOrderAsync(char * accessToken, - Order body, + Order order, void(* handler)(Order, Error, void* ) , void* userData) { return placeOrderHelper(accessToken, - body, + order, handler, userData, true); } bool StoreManager::placeOrderSync(char * accessToken, - Order body, + Order order, void(* handler)(Order, Error, void* ) , void* userData) { return placeOrderHelper(accessToken, - body, + order, handler, userData, false); } diff --git a/samples/client/petstore/tizen/src/StoreManager.h b/samples/client/petstore/tizen/src/StoreManager.h index 9736475b3810..ac172733f735 100644 --- a/samples/client/petstore/tizen/src/StoreManager.h +++ b/samples/client/petstore/tizen/src/StoreManager.h @@ -107,26 +107,26 @@ bool getOrderByIdAsync(char * accessToken, /*! \brief Place an order for a pet. *Synchronous* * * - * \param body order placed for purchasing the pet *Required* + * \param order order placed for purchasing the pet *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool placeOrderSync(char * accessToken, - Order body, + Order order, void(* handler)(Order, Error, void* ) , void* userData); /*! \brief Place an order for a pet. *Asynchronous* * * - * \param body order placed for purchasing the pet *Required* + * \param order order placed for purchasing the pet *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool placeOrderAsync(char * accessToken, - Order body, + Order order, void(* handler)(Order, Error, void* ) , void* userData); diff --git a/samples/client/petstore/tizen/src/Tag.cpp b/samples/client/petstore/tizen/src/Tag.cpp index d2b2ca7068d6..7e1a83ca1188 100644 --- a/samples/client/petstore/tizen/src/Tag.cpp +++ b/samples/client/petstore/tizen/src/Tag.cpp @@ -23,13 +23,8 @@ Tag::~Tag() void Tag::__init() { - // - // //id = long(0); - // - // //name = std::string(); - // } void diff --git a/samples/client/petstore/tizen/src/User.cpp b/samples/client/petstore/tizen/src/User.cpp index d570641dde27..72525576e9c6 100644 --- a/samples/client/petstore/tizen/src/User.cpp +++ b/samples/client/petstore/tizen/src/User.cpp @@ -23,31 +23,14 @@ User::~User() void User::__init() { - // - // //id = long(0); - // - // //username = std::string(); - // - // //firstName = std::string(); - // - // //lastName = std::string(); - // - // //email = std::string(); - // - // //password = std::string(); - // - // //phone = std::string(); - // - // //userStatus = int(0); - // } void diff --git a/samples/client/petstore/tizen/src/UserManager.cpp b/samples/client/petstore/tizen/src/UserManager.cpp index ab3a7e40964f..d2b657211fbe 100644 --- a/samples/client/petstore/tizen/src/UserManager.cpp +++ b/samples/client/petstore/tizen/src/UserManager.cpp @@ -82,7 +82,7 @@ static bool createUserProcessor(MemoryStruct_s p_chunk, long code, char* errorms } static bool createUserHelper(char * accessToken, - User body, + User user, void(* handler)(Error, void* ) , void* userData, bool isAsync) { @@ -94,7 +94,7 @@ static bool createUserHelper(char * accessToken, string accessHeader = "Authorization: Bearer "; accessHeader.append(accessToken); headerList = curl_slist_append(headerList, accessHeader.c_str()); - headerList = curl_slist_append(headerList, "Content-Type: application/json"); + headerList = curl_slist_append(headerList, "Content-Type: */*"); map queryParams; string itemAtq; @@ -104,10 +104,10 @@ static bool createUserHelper(char * accessToken, JsonArray* json_array; if (isprimitive("User")) { - node = converttoJson(&body, "User", ""); + node = converttoJson(&user, "User", ""); } - char *jsonStr = body.toJson(); + char *jsonStr = user.toJson(); node = json_from_string(jsonStr, NULL); g_free(static_cast(jsonStr)); @@ -166,22 +166,22 @@ static bool createUserHelper(char * accessToken, bool UserManager::createUserAsync(char * accessToken, - User body, + User user, void(* handler)(Error, void* ) , void* userData) { return createUserHelper(accessToken, - body, + user, handler, userData, true); } bool UserManager::createUserSync(char * accessToken, - User body, + User user, void(* handler)(Error, void* ) , void* userData) { return createUserHelper(accessToken, - body, + user, handler, userData, false); } @@ -219,7 +219,7 @@ static bool createUsersWithArrayInputProcessor(MemoryStruct_s p_chunk, long code } static bool createUsersWithArrayInputHelper(char * accessToken, - std::list body, + std::list user, void(* handler)(Error, void* ) , void* userData, bool isAsync) { @@ -231,7 +231,7 @@ static bool createUsersWithArrayInputHelper(char * accessToken, string accessHeader = "Authorization: Bearer "; accessHeader.append(accessToken); headerList = curl_slist_append(headerList, accessHeader.c_str()); - headerList = curl_slist_append(headerList, "Content-Type: application/json"); + headerList = curl_slist_append(headerList, "Content-Type: */*"); map queryParams; string itemAtq; @@ -241,12 +241,12 @@ static bool createUsersWithArrayInputHelper(char * accessToken, JsonArray* json_array; //TODO: Map Container if (isprimitive("User")) { - node = converttoJson(&body, "User", "array"); + node = converttoJson(&user, "User", "array"); } else { node = json_node_alloc(); json_array = json_array_new(); for (std::list - ::iterator bodyIter = body.begin(); bodyIter != body.end(); ++bodyIter) { + ::iterator bodyIter = user.begin(); bodyIter != user.end(); ++bodyIter) { User itemAt = (*bodyIter); char *jsonStr = itemAt.toJson(); JsonNode *node_temp = json_from_string(jsonStr, NULL); @@ -315,22 +315,22 @@ static bool createUsersWithArrayInputHelper(char * accessToken, bool UserManager::createUsersWithArrayInputAsync(char * accessToken, - std::list body, + std::list user, void(* handler)(Error, void* ) , void* userData) { return createUsersWithArrayInputHelper(accessToken, - body, + user, handler, userData, true); } bool UserManager::createUsersWithArrayInputSync(char * accessToken, - std::list body, + std::list user, void(* handler)(Error, void* ) , void* userData) { return createUsersWithArrayInputHelper(accessToken, - body, + user, handler, userData, false); } @@ -368,7 +368,7 @@ static bool createUsersWithListInputProcessor(MemoryStruct_s p_chunk, long code, } static bool createUsersWithListInputHelper(char * accessToken, - std::list body, + std::list user, void(* handler)(Error, void* ) , void* userData, bool isAsync) { @@ -380,7 +380,7 @@ static bool createUsersWithListInputHelper(char * accessToken, string accessHeader = "Authorization: Bearer "; accessHeader.append(accessToken); headerList = curl_slist_append(headerList, accessHeader.c_str()); - headerList = curl_slist_append(headerList, "Content-Type: application/json"); + headerList = curl_slist_append(headerList, "Content-Type: */*"); map queryParams; string itemAtq; @@ -390,12 +390,12 @@ static bool createUsersWithListInputHelper(char * accessToken, JsonArray* json_array; //TODO: Map Container if (isprimitive("User")) { - node = converttoJson(&body, "User", "array"); + node = converttoJson(&user, "User", "array"); } else { node = json_node_alloc(); json_array = json_array_new(); for (std::list - ::iterator bodyIter = body.begin(); bodyIter != body.end(); ++bodyIter) { + ::iterator bodyIter = user.begin(); bodyIter != user.end(); ++bodyIter) { User itemAt = (*bodyIter); char *jsonStr = itemAt.toJson(); JsonNode *node_temp = json_from_string(jsonStr, NULL); @@ -464,22 +464,22 @@ static bool createUsersWithListInputHelper(char * accessToken, bool UserManager::createUsersWithListInputAsync(char * accessToken, - std::list body, + std::list user, void(* handler)(Error, void* ) , void* userData) { return createUsersWithListInputHelper(accessToken, - body, + user, handler, userData, true); } bool UserManager::createUsersWithListInputSync(char * accessToken, - std::list body, + std::list user, void(* handler)(Error, void* ) , void* userData) { return createUsersWithListInputHelper(accessToken, - body, + user, handler, userData, false); } @@ -1072,7 +1072,7 @@ static bool updateUserProcessor(MemoryStruct_s p_chunk, long code, char* errorms } static bool updateUserHelper(char * accessToken, - std::string username, User body, + std::string username, User user, void(* handler)(Error, void* ) , void* userData, bool isAsync) { @@ -1084,7 +1084,7 @@ static bool updateUserHelper(char * accessToken, string accessHeader = "Authorization: Bearer "; accessHeader.append(accessToken); headerList = curl_slist_append(headerList, accessHeader.c_str()); - headerList = curl_slist_append(headerList, "Content-Type: application/json"); + headerList = curl_slist_append(headerList, "Content-Type: */*"); map queryParams; string itemAtq; @@ -1094,10 +1094,10 @@ static bool updateUserHelper(char * accessToken, JsonArray* json_array; if (isprimitive("User")) { - node = converttoJson(&body, "User", ""); + node = converttoJson(&user, "User", ""); } - char *jsonStr = body.toJson(); + char *jsonStr = user.toJson(); node = json_from_string(jsonStr, NULL); g_free(static_cast(jsonStr)); @@ -1162,22 +1162,22 @@ static bool updateUserHelper(char * accessToken, bool UserManager::updateUserAsync(char * accessToken, - std::string username, User body, + std::string username, User user, void(* handler)(Error, void* ) , void* userData) { return updateUserHelper(accessToken, - username, body, + username, user, handler, userData, true); } bool UserManager::updateUserSync(char * accessToken, - std::string username, User body, + std::string username, User user, void(* handler)(Error, void* ) , void* userData) { return updateUserHelper(accessToken, - username, body, + username, user, handler, userData, false); } diff --git a/samples/client/petstore/tizen/src/UserManager.h b/samples/client/petstore/tizen/src/UserManager.h index 4c9a3a5f7ddf..e320dadb2d69 100644 --- a/samples/client/petstore/tizen/src/UserManager.h +++ b/samples/client/petstore/tizen/src/UserManager.h @@ -6,7 +6,6 @@ #include #include #include "User.h" -#include #include "Error.h" /** \defgroup Operations API Endpoints @@ -28,26 +27,26 @@ class UserManager { /*! \brief Create user. *Synchronous* * * This can only be done by the logged in user. - * \param body Created user object *Required* + * \param user Created user object *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool createUserSync(char * accessToken, - User body, + User user, void(* handler)(Error, void* ) , void* userData); /*! \brief Create user. *Asynchronous* * * This can only be done by the logged in user. - * \param body Created user object *Required* + * \param user Created user object *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool createUserAsync(char * accessToken, - User body, + User user, void(* handler)(Error, void* ) , void* userData); @@ -55,26 +54,26 @@ bool createUserAsync(char * accessToken, /*! \brief Creates list of users with given input array. *Synchronous* * * - * \param body List of user object *Required* + * \param user List of user object *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool createUsersWithArrayInputSync(char * accessToken, - std::list body, + std::list user, void(* handler)(Error, void* ) , void* userData); /*! \brief Creates list of users with given input array. *Asynchronous* * * - * \param body List of user object *Required* + * \param user List of user object *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool createUsersWithArrayInputAsync(char * accessToken, - std::list body, + std::list user, void(* handler)(Error, void* ) , void* userData); @@ -82,26 +81,26 @@ bool createUsersWithArrayInputAsync(char * accessToken, /*! \brief Creates list of users with given input array. *Synchronous* * * - * \param body List of user object *Required* + * \param user List of user object *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool createUsersWithListInputSync(char * accessToken, - std::list body, + std::list user, void(* handler)(Error, void* ) , void* userData); /*! \brief Creates list of users with given input array. *Asynchronous* * * - * \param body List of user object *Required* + * \param user List of user object *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool createUsersWithListInputAsync(char * accessToken, - std::list body, + std::list user, void(* handler)(Error, void* ) , void* userData); @@ -136,7 +135,7 @@ bool deleteUserAsync(char * accessToken, /*! \brief Get user by user name. *Synchronous* * * - * \param username The name that needs to be fetched. Use user1 for testing. *Required* + * \param username The name that needs to be fetched. Use user1 for testing. *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. @@ -149,7 +148,7 @@ bool getUserByNameSync(char * accessToken, /*! \brief Get user by user name. *Asynchronous* * * - * \param username The name that needs to be fetched. Use user1 for testing. *Required* + * \param username The name that needs to be fetched. Use user1 for testing. *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. @@ -218,13 +217,13 @@ bool logoutUserAsync(char * accessToken, * * This can only be done by the logged in user. * \param username name that need to be deleted *Required* - * \param body Updated user object *Required* + * \param user Updated user object *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool updateUserSync(char * accessToken, - std::string username, User body, + std::string username, User user, void(* handler)(Error, void* ) , void* userData); @@ -232,13 +231,13 @@ bool updateUserSync(char * accessToken, * * This can only be done by the logged in user. * \param username name that need to be deleted *Required* - * \param body Updated user object *Required* + * \param user Updated user object *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool updateUserAsync(char * accessToken, - std::string username, User body, + std::string username, User user, void(* handler)(Error, void* ) , void* userData); diff --git a/samples/client/petstore/typescript-angular-v2/default/api.module.ts b/samples/client/petstore/typescript-angular-v2/default/api.module.ts index 1504d60e630a..d321b1180dee 100644 --- a/samples/client/petstore/typescript-angular-v2/default/api.module.ts +++ b/samples/client/petstore/typescript-angular-v2/default/api.module.ts @@ -21,7 +21,7 @@ export class ApiModule { return { ngModule: ApiModule, providers: [ { provide: Configuration, useFactory: configurationFactory } ] - } + }; } constructor( @Optional() @SkipSelf() parentModule: ApiModule, diff --git a/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts index 30354b574375..0f487e7b1a03 100644 --- a/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts @@ -50,7 +50,7 @@ export class PetService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -207,7 +207,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -218,17 +218,17 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/json', 'application/xml' ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -266,7 +266,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -277,13 +277,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -319,7 +319,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -330,13 +330,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -373,7 +373,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -384,13 +384,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -430,13 +430,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -467,7 +467,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -478,17 +478,17 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/json', 'application/xml' ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -524,7 +524,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -535,13 +535,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/x-www-form-urlencoded' ]; @@ -598,7 +598,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -608,13 +608,13 @@ export class PetService { let httpHeaderAccepts: string[] = [ 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'multipart/form-data' ]; diff --git a/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts index 5c4d7ee59547..443d2ba8480e 100644 --- a/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts @@ -49,7 +49,7 @@ export class StoreService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -139,13 +139,13 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -179,13 +179,13 @@ export class StoreService { let httpHeaderAccepts: string[] = [ 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -219,13 +219,13 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -259,15 +259,15 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts index fe2b4f7b6e78..04225a20df65 100644 --- a/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts @@ -49,7 +49,7 @@ export class UserService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -124,7 +124,7 @@ export class UserService { /** * * @summary Get user by user name - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ public getUserByName(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { return this.getUserByNameWithHttpInfo(username, extraHttpRequestParams) @@ -205,15 +205,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -250,15 +250,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -295,15 +295,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -340,13 +340,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -365,7 +365,7 @@ export class UserService { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { @@ -380,13 +380,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -432,13 +432,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -469,13 +469,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -513,15 +513,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/default/model/order.ts b/samples/client/petstore/typescript-angular-v2/default/model/order.ts index 6a1e1fd6bcfd..c4ebae79be9b 100644 --- a/samples/client/petstore/typescript-angular-v2/default/model/order.ts +++ b/samples/client/petstore/typescript-angular-v2/default/model/order.ts @@ -31,5 +31,5 @@ export namespace Order { Placed: 'placed' as StatusEnum, Approved: 'approved' as StatusEnum, Delivered: 'delivered' as StatusEnum - } + }; } diff --git a/samples/client/petstore/typescript-angular-v2/default/model/pet.ts b/samples/client/petstore/typescript-angular-v2/default/model/pet.ts index b8b659008af8..9a8caa651fa9 100644 --- a/samples/client/petstore/typescript-angular-v2/default/model/pet.ts +++ b/samples/client/petstore/typescript-angular-v2/default/model/pet.ts @@ -33,5 +33,5 @@ export namespace Pet { Available: 'available' as StatusEnum, Pending: 'pending' as StatusEnum, Sold: 'sold' as StatusEnum - } + }; } diff --git a/samples/client/petstore/typescript-angular-v2/npm/api.module.ts b/samples/client/petstore/typescript-angular-v2/npm/api.module.ts index 1504d60e630a..d321b1180dee 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/api.module.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/api.module.ts @@ -21,7 +21,7 @@ export class ApiModule { return { ngModule: ApiModule, providers: [ { provide: Configuration, useFactory: configurationFactory } ] - } + }; } constructor( @Optional() @SkipSelf() parentModule: ApiModule, diff --git a/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts index 30354b574375..0f487e7b1a03 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts @@ -50,7 +50,7 @@ export class PetService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -207,7 +207,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -218,17 +218,17 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/json', 'application/xml' ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -266,7 +266,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -277,13 +277,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -319,7 +319,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -330,13 +330,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -373,7 +373,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -384,13 +384,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -430,13 +430,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -467,7 +467,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -478,17 +478,17 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/json', 'application/xml' ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -524,7 +524,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -535,13 +535,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/x-www-form-urlencoded' ]; @@ -598,7 +598,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -608,13 +608,13 @@ export class PetService { let httpHeaderAccepts: string[] = [ 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'multipart/form-data' ]; diff --git a/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts index 5c4d7ee59547..443d2ba8480e 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts @@ -49,7 +49,7 @@ export class StoreService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -139,13 +139,13 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -179,13 +179,13 @@ export class StoreService { let httpHeaderAccepts: string[] = [ 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -219,13 +219,13 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -259,15 +259,15 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts index fe2b4f7b6e78..04225a20df65 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts @@ -49,7 +49,7 @@ export class UserService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -124,7 +124,7 @@ export class UserService { /** * * @summary Get user by user name - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ public getUserByName(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { return this.getUserByNameWithHttpInfo(username, extraHttpRequestParams) @@ -205,15 +205,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -250,15 +250,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -295,15 +295,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -340,13 +340,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -365,7 +365,7 @@ export class UserService { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { @@ -380,13 +380,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -432,13 +432,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -469,13 +469,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -513,15 +513,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/npm/model/order.ts b/samples/client/petstore/typescript-angular-v2/npm/model/order.ts index 6a1e1fd6bcfd..c4ebae79be9b 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/model/order.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/model/order.ts @@ -31,5 +31,5 @@ export namespace Order { Placed: 'placed' as StatusEnum, Approved: 'approved' as StatusEnum, Delivered: 'delivered' as StatusEnum - } + }; } diff --git a/samples/client/petstore/typescript-angular-v2/npm/model/pet.ts b/samples/client/petstore/typescript-angular-v2/npm/model/pet.ts index b8b659008af8..9a8caa651fa9 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/model/pet.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/model/pet.ts @@ -33,5 +33,5 @@ export namespace Pet { Available: 'available' as StatusEnum, Pending: 'pending' as StatusEnum, Sold: 'sold' as StatusEnum - } + }; } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api.module.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api.module.ts index 1504d60e630a..d321b1180dee 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api.module.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api.module.ts @@ -21,7 +21,7 @@ export class ApiModule { return { ngModule: ApiModule, providers: [ { provide: Configuration, useFactory: configurationFactory } ] - } + }; } constructor( @Optional() @SkipSelf() parentModule: ApiModule, diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts index 565e6d3dbe4d..c6bad17ba2a3 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts @@ -51,7 +51,7 @@ export class PetService implements PetServiceInterface { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -208,7 +208,7 @@ export class PetService implements PetServiceInterface { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -219,17 +219,17 @@ export class PetService implements PetServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/json', 'application/xml' ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -267,7 +267,7 @@ export class PetService implements PetServiceInterface { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -278,13 +278,13 @@ export class PetService implements PetServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -320,7 +320,7 @@ export class PetService implements PetServiceInterface { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -331,13 +331,13 @@ export class PetService implements PetServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -374,7 +374,7 @@ export class PetService implements PetServiceInterface { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -385,13 +385,13 @@ export class PetService implements PetServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -431,13 +431,13 @@ export class PetService implements PetServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -468,7 +468,7 @@ export class PetService implements PetServiceInterface { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -479,17 +479,17 @@ export class PetService implements PetServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/json', 'application/xml' ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -525,7 +525,7 @@ export class PetService implements PetServiceInterface { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -536,13 +536,13 @@ export class PetService implements PetServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/x-www-form-urlencoded' ]; @@ -599,7 +599,7 @@ export class PetService implements PetServiceInterface { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -609,13 +609,13 @@ export class PetService implements PetServiceInterface { let httpHeaderAccepts: string[] = [ 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'multipart/form-data' ]; diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts index 185de6d5e09d..424d17329608 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts @@ -50,7 +50,7 @@ export class StoreService implements StoreServiceInterface { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -140,13 +140,13 @@ export class StoreService implements StoreServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -180,13 +180,13 @@ export class StoreService implements StoreServiceInterface { let httpHeaderAccepts: string[] = [ 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -220,13 +220,13 @@ export class StoreService implements StoreServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -260,15 +260,15 @@ export class StoreService implements StoreServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts index ccbb653e9ef9..03ea7ca29492 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts @@ -50,7 +50,7 @@ export class UserService implements UserServiceInterface { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -125,7 +125,7 @@ export class UserService implements UserServiceInterface { /** * * @summary Get user by user name - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ public getUserByName(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { return this.getUserByNameWithHttpInfo(username, extraHttpRequestParams) @@ -206,15 +206,15 @@ export class UserService implements UserServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -251,15 +251,15 @@ export class UserService implements UserServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -296,15 +296,15 @@ export class UserService implements UserServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -341,13 +341,13 @@ export class UserService implements UserServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -366,7 +366,7 @@ export class UserService implements UserServiceInterface { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { @@ -381,13 +381,13 @@ export class UserService implements UserServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -433,13 +433,13 @@ export class UserService implements UserServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -470,13 +470,13 @@ export class UserService implements UserServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -514,15 +514,15 @@ export class UserService implements UserServiceInterface { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.serviceInterface.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.serviceInterface.ts index f68e221df9a8..24a7c857b694 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.serviceInterface.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.serviceInterface.ts @@ -53,7 +53,7 @@ export interface UserServiceInterface { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ getUserByName(username: string, extraHttpRequestParams?: any): Observable; diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/order.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/order.ts index 6a1e1fd6bcfd..c4ebae79be9b 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/order.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/order.ts @@ -31,5 +31,5 @@ export namespace Order { Placed: 'placed' as StatusEnum, Approved: 'approved' as StatusEnum, Delivered: 'delivered' as StatusEnum - } + }; } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/pet.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/pet.ts index b8b659008af8..9a8caa651fa9 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/pet.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/pet.ts @@ -33,5 +33,5 @@ export namespace Pet { Available: 'available' as StatusEnum, Pending: 'pending' as StatusEnum, Sold: 'sold' as StatusEnum - } + }; } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/api.module.ts b/samples/client/petstore/typescript-angular-v4.3/npm/api.module.ts index 72f2a15ddcbe..8487243a83b1 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/api.module.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/api.module.ts @@ -21,7 +21,7 @@ export class ApiModule { return { ngModule: ApiModule, providers: [ { provide: Configuration, useFactory: configurationFactory } ] - } + }; } constructor( @Optional() @SkipSelf() parentModule: ApiModule, diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts index 5dc987751bc2..18563adb1b3b 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts @@ -48,7 +48,7 @@ export class PetService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -76,7 +76,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers = headers.set('Authorization', 'Bearer ' + accessToken); @@ -87,19 +87,19 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/json', 'application/xml' ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { - headers = headers.set("Content-Type", httpContentTypeSelected); + headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.post(`${this.basePath}/pet`, @@ -136,7 +136,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers = headers.set('Authorization', 'Bearer ' + accessToken); @@ -147,13 +147,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; return this.httpClient.delete(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, @@ -190,7 +190,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers = headers.set('Authorization', 'Bearer ' + accessToken); @@ -201,13 +201,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; return this.httpClient.get>(`${this.basePath}/pet/findByStatus`, @@ -245,7 +245,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers = headers.set('Authorization', 'Bearer ' + accessToken); @@ -256,13 +256,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; return this.httpClient.get>(`${this.basePath}/pet/findByTags`, @@ -303,13 +303,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; return this.httpClient.get(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, @@ -341,7 +341,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers = headers.set('Authorization', 'Bearer ' + accessToken); @@ -352,19 +352,19 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/json', 'application/xml' ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { - headers = headers.set("Content-Type", httpContentTypeSelected); + headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.put(`${this.basePath}/pet`, @@ -399,7 +399,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers = headers.set('Authorization', 'Bearer ' + accessToken); @@ -410,13 +410,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/x-www-form-urlencoded' ]; @@ -470,7 +470,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers = headers.set('Authorization', 'Bearer ' + accessToken); @@ -480,13 +480,13 @@ export class PetService { let httpHeaderAccepts: string[] = [ 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'multipart/form-data' ]; diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts index 7c5364e471c1..03016b73c9d8 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts @@ -47,7 +47,7 @@ export class StoreService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -78,13 +78,13 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; return this.httpClient.delete(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, @@ -119,13 +119,13 @@ export class StoreService { let httpHeaderAccepts: string[] = [ 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; return this.httpClient.get<{ [key: string]: number; }>(`${this.basePath}/store/inventory`, @@ -160,13 +160,13 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; return this.httpClient.get(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, @@ -201,17 +201,17 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { - headers = headers.set("Content-Type", httpContentTypeSelected); + headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.post(`${this.basePath}/store/order`, diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts index edc7a4b42983..9fba356e6185 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts @@ -47,7 +47,7 @@ export class UserService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -78,17 +78,17 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { - headers = headers.set("Content-Type", httpContentTypeSelected); + headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.post(`${this.basePath}/user`, @@ -124,17 +124,17 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { - headers = headers.set("Content-Type", httpContentTypeSelected); + headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.post(`${this.basePath}/user/createWithArray`, @@ -170,17 +170,17 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { - headers = headers.set("Content-Type", httpContentTypeSelected); + headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.post(`${this.basePath}/user/createWithList`, @@ -216,13 +216,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; return this.httpClient.delete(`${this.basePath}/user/${encodeURIComponent(String(username))}`, @@ -238,7 +238,7 @@ export class UserService { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ @@ -257,13 +257,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; return this.httpClient.get(`${this.basePath}/user/${encodeURIComponent(String(username))}`, @@ -310,13 +310,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; return this.httpClient.get(`${this.basePath}/user/login`, @@ -348,13 +348,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; return this.httpClient.get(`${this.basePath}/user/logout`, @@ -393,17 +393,17 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers = headers.set("Accept", httpHeaderAcceptSelected); + headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { - headers = headers.set("Content-Type", httpContentTypeSelected); + headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.put(`${this.basePath}/user/${encodeURIComponent(String(username))}`, diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/model/order.ts b/samples/client/petstore/typescript-angular-v4.3/npm/model/order.ts index 6a1e1fd6bcfd..c4ebae79be9b 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/model/order.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/model/order.ts @@ -31,5 +31,5 @@ export namespace Order { Placed: 'placed' as StatusEnum, Approved: 'approved' as StatusEnum, Delivered: 'delivered' as StatusEnum - } + }; } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/model/pet.ts b/samples/client/petstore/typescript-angular-v4.3/npm/model/pet.ts index b8b659008af8..9a8caa651fa9 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/model/pet.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/model/pet.ts @@ -33,5 +33,5 @@ export namespace Pet { Available: 'available' as StatusEnum, Pending: 'pending' as StatusEnum, Sold: 'sold' as StatusEnum - } + }; } diff --git a/samples/client/petstore/typescript-angular-v4/npm/api.module.ts b/samples/client/petstore/typescript-angular-v4/npm/api.module.ts index 1504d60e630a..d321b1180dee 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/api.module.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/api.module.ts @@ -21,7 +21,7 @@ export class ApiModule { return { ngModule: ApiModule, providers: [ { provide: Configuration, useFactory: configurationFactory } ] - } + }; } constructor( @Optional() @SkipSelf() parentModule: ApiModule, diff --git a/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts index 30354b574375..0f487e7b1a03 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts @@ -50,7 +50,7 @@ export class PetService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -207,7 +207,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -218,17 +218,17 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/json', 'application/xml' ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -266,7 +266,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -277,13 +277,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -319,7 +319,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -330,13 +330,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -373,7 +373,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -384,13 +384,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -430,13 +430,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -467,7 +467,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -478,17 +478,17 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/json', 'application/xml' ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -524,7 +524,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -535,13 +535,13 @@ export class PetService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/x-www-form-urlencoded' ]; @@ -598,7 +598,7 @@ export class PetService { // authentication (petstore_auth) required if (this.configuration.accessToken) { - let accessToken = typeof this.configuration.accessToken === 'function' + const accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); @@ -608,13 +608,13 @@ export class PetService { let httpHeaderAccepts: string[] = [ 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'multipart/form-data' ]; diff --git a/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts index 5c4d7ee59547..443d2ba8480e 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts @@ -49,7 +49,7 @@ export class StoreService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -139,13 +139,13 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -179,13 +179,13 @@ export class StoreService { let httpHeaderAccepts: string[] = [ 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -219,13 +219,13 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -259,15 +259,15 @@ export class StoreService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } diff --git a/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts index fe2b4f7b6e78..04225a20df65 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts @@ -49,7 +49,7 @@ export class UserService { */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; - for (let consume of consumes) { + for (const consume of consumes) { if (form === consume) { return true; } @@ -124,7 +124,7 @@ export class UserService { /** * * @summary Get user by user name - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ public getUserByName(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { return this.getUserByNameWithHttpInfo(username, extraHttpRequestParams) @@ -205,15 +205,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -250,15 +250,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -295,15 +295,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } @@ -340,13 +340,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -365,7 +365,7 @@ export class UserService { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { @@ -380,13 +380,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -432,13 +432,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -469,13 +469,13 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -513,15 +513,15 @@ export class UserService { 'application/xml', 'application/json' ]; - let httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected != undefined) { - headers.set("Accept", httpHeaderAcceptSelected); + headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ ]; - let httpContentTypeSelected:string | undefined = this.configuration.selectHeaderContentType(consumes); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected != undefined) { headers.set('Content-Type', httpContentTypeSelected); } diff --git a/samples/client/petstore/typescript-angular-v4/npm/model/order.ts b/samples/client/petstore/typescript-angular-v4/npm/model/order.ts index 6a1e1fd6bcfd..c4ebae79be9b 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/model/order.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/model/order.ts @@ -31,5 +31,5 @@ export namespace Order { Placed: 'placed' as StatusEnum, Approved: 'approved' as StatusEnum, Delivered: 'delivered' as StatusEnum - } + }; } diff --git a/samples/client/petstore/typescript-angular-v4/npm/model/pet.ts b/samples/client/petstore/typescript-angular-v4/npm/model/pet.ts index b8b659008af8..9a8caa651fa9 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/model/pet.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/model/pet.ts @@ -33,5 +33,5 @@ export namespace Pet { Available: 'available' as StatusEnum, Pending: 'pending' as StatusEnum, Sold: 'sold' as StatusEnum - } + }; } diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts index 72e705621fa2..7b89d8a61f52 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -210,13 +210,13 @@ export interface Pet { name: string; /** * - * @type {Array<string>} + * @type {Array} * @memberof Pet */ photoUrls: Array; /** * - * @type {Array<Tag>} + * @type {Array} * @memberof Pet */ tags?: Array; @@ -414,7 +414,7 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -455,7 +455,7 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {Array<string>} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -726,7 +726,7 @@ export const PetApiFp = function(configuration?: Configuration) { /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -745,7 +745,7 @@ export const PetApiFp = function(configuration?: Configuration) { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {Array<string>} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -874,7 +874,7 @@ export const PetApiFactory = function (configuration?: Configuration, fetch?: Fe /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -884,7 +884,7 @@ export const PetApiFactory = function (configuration?: Configuration, fetch?: Fe /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {Array<string>} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -948,7 +948,7 @@ export class PetApi extends BaseAPI { /** * * @summary Add a new pet to the store - * @param {} body Pet object that needs to be added to the store + * @param {Pet} body Pet object that needs to be added to the store * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -960,8 +960,8 @@ export class PetApi extends BaseAPI { /** * * @summary Deletes a pet - * @param {} petId Pet id to delete - * @param {} [apiKey] + * @param {number} petId Pet id to delete + * @param {string} [apiKey] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -973,7 +973,7 @@ export class PetApi extends BaseAPI { /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -985,7 +985,7 @@ export class PetApi extends BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -997,7 +997,7 @@ export class PetApi extends BaseAPI { /** * Returns a single pet * @summary Find pet by ID - * @param {} petId ID of pet to return + * @param {number} petId ID of pet to return * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1009,7 +1009,7 @@ export class PetApi extends BaseAPI { /** * * @summary Update an existing pet - * @param {} body Pet object that needs to be added to the store + * @param {Pet} body Pet object that needs to be added to the store * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1021,9 +1021,9 @@ export class PetApi extends BaseAPI { /** * * @summary Updates a pet in the store with form data - * @param {} petId ID of pet that needs to be updated - * @param {} [name] Updated name of the pet - * @param {} [status] Updated status of the pet + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1035,9 +1035,9 @@ export class PetApi extends BaseAPI { /** * * @summary uploads an image - * @param {} petId ID of pet to update - * @param {} [additionalMetadata] Additional data to pass to server - * @param {} [file] file to upload + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1320,7 +1320,7 @@ export class StoreApi extends BaseAPI { /** * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @summary Delete purchase order by ID - * @param {} orderId ID of the order that needs to be deleted + * @param {string} orderId ID of the order that needs to be deleted * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StoreApi @@ -1343,7 +1343,7 @@ export class StoreApi extends BaseAPI { /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @summary Find purchase order by ID - * @param {} orderId ID of pet that needs to be fetched + * @param {number} orderId ID of pet that needs to be fetched * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StoreApi @@ -1355,7 +1355,7 @@ export class StoreApi extends BaseAPI { /** * * @summary Place an order for a pet - * @param {} body order placed for purchasing the pet + * @param {Order} body order placed for purchasing the pet * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StoreApi @@ -1407,7 +1407,7 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1439,7 +1439,7 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1500,7 +1500,7 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) /** * * @summary Get user by user name - * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1659,7 +1659,7 @@ export const UserApiFp = function(configuration?: Configuration) { /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1678,7 +1678,7 @@ export const UserApiFp = function(configuration?: Configuration) { /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1716,7 +1716,7 @@ export const UserApiFp = function(configuration?: Configuration) { /** * * @summary Get user by user name - * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1812,7 +1812,7 @@ export const UserApiFactory = function (configuration?: Configuration, fetch?: F /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1822,7 +1822,7 @@ export const UserApiFactory = function (configuration?: Configuration, fetch?: F /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1842,7 +1842,7 @@ export const UserApiFactory = function (configuration?: Configuration, fetch?: F /** * * @summary Get user by user name - * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1893,7 +1893,7 @@ export class UserApi extends BaseAPI { /** * This can only be done by the logged in user. * @summary Create user - * @param {} body Created user object + * @param {User} body Created user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1905,7 +1905,7 @@ export class UserApi extends BaseAPI { /** * * @summary Creates list of users with given input array - * @param {} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1917,7 +1917,7 @@ export class UserApi extends BaseAPI { /** * * @summary Creates list of users with given input array - * @param {} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1929,7 +1929,7 @@ export class UserApi extends BaseAPI { /** * This can only be done by the logged in user. * @summary Delete user - * @param {} username The name that needs to be deleted + * @param {string} username The name that needs to be deleted * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1941,7 +1941,7 @@ export class UserApi extends BaseAPI { /** * * @summary Get user by user name - * @param {} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1953,8 +1953,8 @@ export class UserApi extends BaseAPI { /** * * @summary Logs user into the system - * @param {} username The user name for login - * @param {} password The password for login in clear text + * @param {string} username The user name for login + * @param {string} password The password for login in clear text * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1977,8 +1977,8 @@ export class UserApi extends BaseAPI { /** * This can only be done by the logged in user. * @summary Updated user - * @param {} username name that need to be deleted - * @param {} body Updated user object + * @param {string} username name that need to be deleted + * @param {User} body Updated user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts index 72e705621fa2..7b89d8a61f52 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -210,13 +210,13 @@ export interface Pet { name: string; /** * - * @type {Array<string>} + * @type {Array} * @memberof Pet */ photoUrls: Array; /** * - * @type {Array<Tag>} + * @type {Array} * @memberof Pet */ tags?: Array; @@ -414,7 +414,7 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -455,7 +455,7 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {Array<string>} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -726,7 +726,7 @@ export const PetApiFp = function(configuration?: Configuration) { /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -745,7 +745,7 @@ export const PetApiFp = function(configuration?: Configuration) { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {Array<string>} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -874,7 +874,7 @@ export const PetApiFactory = function (configuration?: Configuration, fetch?: Fe /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -884,7 +884,7 @@ export const PetApiFactory = function (configuration?: Configuration, fetch?: Fe /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {Array<string>} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -948,7 +948,7 @@ export class PetApi extends BaseAPI { /** * * @summary Add a new pet to the store - * @param {} body Pet object that needs to be added to the store + * @param {Pet} body Pet object that needs to be added to the store * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -960,8 +960,8 @@ export class PetApi extends BaseAPI { /** * * @summary Deletes a pet - * @param {} petId Pet id to delete - * @param {} [apiKey] + * @param {number} petId Pet id to delete + * @param {string} [apiKey] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -973,7 +973,7 @@ export class PetApi extends BaseAPI { /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -985,7 +985,7 @@ export class PetApi extends BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -997,7 +997,7 @@ export class PetApi extends BaseAPI { /** * Returns a single pet * @summary Find pet by ID - * @param {} petId ID of pet to return + * @param {number} petId ID of pet to return * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1009,7 +1009,7 @@ export class PetApi extends BaseAPI { /** * * @summary Update an existing pet - * @param {} body Pet object that needs to be added to the store + * @param {Pet} body Pet object that needs to be added to the store * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1021,9 +1021,9 @@ export class PetApi extends BaseAPI { /** * * @summary Updates a pet in the store with form data - * @param {} petId ID of pet that needs to be updated - * @param {} [name] Updated name of the pet - * @param {} [status] Updated status of the pet + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1035,9 +1035,9 @@ export class PetApi extends BaseAPI { /** * * @summary uploads an image - * @param {} petId ID of pet to update - * @param {} [additionalMetadata] Additional data to pass to server - * @param {} [file] file to upload + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1320,7 +1320,7 @@ export class StoreApi extends BaseAPI { /** * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @summary Delete purchase order by ID - * @param {} orderId ID of the order that needs to be deleted + * @param {string} orderId ID of the order that needs to be deleted * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StoreApi @@ -1343,7 +1343,7 @@ export class StoreApi extends BaseAPI { /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @summary Find purchase order by ID - * @param {} orderId ID of pet that needs to be fetched + * @param {number} orderId ID of pet that needs to be fetched * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StoreApi @@ -1355,7 +1355,7 @@ export class StoreApi extends BaseAPI { /** * * @summary Place an order for a pet - * @param {} body order placed for purchasing the pet + * @param {Order} body order placed for purchasing the pet * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StoreApi @@ -1407,7 +1407,7 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1439,7 +1439,7 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1500,7 +1500,7 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) /** * * @summary Get user by user name - * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1659,7 +1659,7 @@ export const UserApiFp = function(configuration?: Configuration) { /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1678,7 +1678,7 @@ export const UserApiFp = function(configuration?: Configuration) { /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1716,7 +1716,7 @@ export const UserApiFp = function(configuration?: Configuration) { /** * * @summary Get user by user name - * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1812,7 +1812,7 @@ export const UserApiFactory = function (configuration?: Configuration, fetch?: F /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1822,7 +1822,7 @@ export const UserApiFactory = function (configuration?: Configuration, fetch?: F /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1842,7 +1842,7 @@ export const UserApiFactory = function (configuration?: Configuration, fetch?: F /** * * @summary Get user by user name - * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1893,7 +1893,7 @@ export class UserApi extends BaseAPI { /** * This can only be done by the logged in user. * @summary Create user - * @param {} body Created user object + * @param {User} body Created user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1905,7 +1905,7 @@ export class UserApi extends BaseAPI { /** * * @summary Creates list of users with given input array - * @param {} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1917,7 +1917,7 @@ export class UserApi extends BaseAPI { /** * * @summary Creates list of users with given input array - * @param {} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1929,7 +1929,7 @@ export class UserApi extends BaseAPI { /** * This can only be done by the logged in user. * @summary Delete user - * @param {} username The name that needs to be deleted + * @param {string} username The name that needs to be deleted * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1941,7 +1941,7 @@ export class UserApi extends BaseAPI { /** * * @summary Get user by user name - * @param {} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1953,8 +1953,8 @@ export class UserApi extends BaseAPI { /** * * @summary Logs user into the system - * @param {} username The user name for login - * @param {} password The password for login in clear text + * @param {string} username The user name for login + * @param {string} password The password for login in clear text * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1977,8 +1977,8 @@ export class UserApi extends BaseAPI { /** * This can only be done by the logged in user. * @summary Updated user - * @param {} username name that need to be deleted - * @param {} body Updated user object + * @param {string} username name that need to be deleted + * @param {User} body Updated user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/.gitignore b/samples/client/petstore/typescript-fetch/builds/with-interfaces/.gitignore new file mode 100644 index 000000000000..35e2fb2b02ed --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/.swagger-codegen-ignore b/samples/client/petstore/typescript-fetch/builds/with-interfaces/.swagger-codegen-ignore new file mode 100644 index 000000000000..c5fa491b4c55 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/typescript-fetch/builds/with-interfaces/.swagger-codegen/VERSION b/samples/client/petstore/typescript-fetch/builds/with-interfaces/.swagger-codegen/VERSION new file mode 100644 index 000000000000..855ff9501eb8 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/api.ts b/samples/client/petstore/typescript-fetch/builds/with-interfaces/api.ts new file mode 100644 index 000000000000..9c9de6dd0125 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/api.ts @@ -0,0 +1,2220 @@ +/// +// tslint:disable +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +import * as url from "url"; +import * as portableFetch from "portable-fetch"; +import { Configuration } from "./configuration"; + +const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); + +/** + * + * @export + */ +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +/** + * + * @export + * @interface FetchAPI + */ +export interface FetchAPI { + (url: string, init?: any): Promise; +} + +/** + * + * @export + * @interface FetchArgs + */ +export interface FetchArgs { + url: string; + options: any; +} + +/** + * + * @export + * @class BaseAPI + */ +export class BaseAPI { + protected configuration: Configuration; + + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = portableFetch) { + if (configuration) { + this.configuration = configuration; + this.basePath = configuration.basePath || this.basePath; + } + } +}; + +/** + * + * @export + * @class RequiredError + * @extends {Error} + */ +export class RequiredError extends Error { + name: "RequiredError" + constructor(public field: string, msg?: string) { + super(msg); + } +} + +/** + * Describes the result of uploading an image resource + * @export + * @interface ApiResponse + */ +export interface ApiResponse { + /** + * + * @type {number} + * @memberof ApiResponse + */ + code?: number; + /** + * + * @type {string} + * @memberof ApiResponse + */ + type?: string; + /** + * + * @type {string} + * @memberof ApiResponse + */ + message?: string; +} + +/** + * A category for a pet + * @export + * @interface Category + */ +export interface Category { + /** + * + * @type {number} + * @memberof Category + */ + id?: number; + /** + * + * @type {string} + * @memberof Category + */ + name?: string; +} + +/** + * An order for a pets from the pet store + * @export + * @interface Order + */ +export interface Order { + /** + * + * @type {number} + * @memberof Order + */ + id?: number; + /** + * + * @type {number} + * @memberof Order + */ + petId?: number; + /** + * + * @type {number} + * @memberof Order + */ + quantity?: number; + /** + * + * @type {Date} + * @memberof Order + */ + shipDate?: Date; + /** + * Order Status + * @type {string} + * @memberof Order + */ + status?: Order.StatusEnum; + /** + * + * @type {boolean} + * @memberof Order + */ + complete?: boolean; +} + +/** + * @export + * @namespace Order + */ +export namespace Order { + /** + * @export + * @enum {string} + */ + export enum StatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' + } +} + +/** + * A pet for sale in the pet store + * @export + * @interface Pet + */ +export interface Pet { + /** + * + * @type {number} + * @memberof Pet + */ + id?: number; + /** + * + * @type {Category} + * @memberof Pet + */ + category?: Category; + /** + * + * @type {string} + * @memberof Pet + */ + name: string; + /** + * + * @type {Array} + * @memberof Pet + */ + photoUrls: Array; + /** + * + * @type {Array} + * @memberof Pet + */ + tags?: Array; + /** + * pet status in the store + * @type {string} + * @memberof Pet + */ + status?: Pet.StatusEnum; +} + +/** + * @export + * @namespace Pet + */ +export namespace Pet { + /** + * @export + * @enum {string} + */ + export enum StatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' + } +} + +/** + * A tag for a pet + * @export + * @interface Tag + */ +export interface Tag { + /** + * + * @type {number} + * @memberof Tag + */ + id?: number; + /** + * + * @type {string} + * @memberof Tag + */ + name?: string; +} + +/** + * A User who is purchasing from the pet store + * @export + * @interface User + */ +export interface User { + /** + * + * @type {number} + * @memberof User + */ + id?: number; + /** + * + * @type {string} + * @memberof User + */ + username?: string; + /** + * + * @type {string} + * @memberof User + */ + firstName?: string; + /** + * + * @type {string} + * @memberof User + */ + lastName?: string; + /** + * + * @type {string} + * @memberof User + */ + email?: string; + /** + * + * @type {string} + * @memberof User + */ + password?: string; + /** + * + * @type {string} + * @memberof User + */ + phone?: string; + /** + * User Status + * @type {number} + * @memberof User + */ + userStatus?: number; +} + + +/** + * PetApi - fetch parameter creator + * @export + */ +export const PetApiFetchParamCreator = function (configuration?: Configuration) { + return { + /** + * + * @summary Add a new pet to the store + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + addPet(body: Pet, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling addPet.'); + } + const localVarPath = `/pet`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("Pet" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Deletes a pet + * @param {number} petId Pet id to delete + * @param {string} [apiKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deletePet(petId: number, apiKey?: string, options: any = {}): FetchArgs { + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError('petId','Required parameter petId was null or undefined when calling deletePet.'); + } + const localVarPath = `/pet/{petId}` + .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + if (apiKey !== undefined && apiKey !== null) { + localVarHeaderParameter['api_key'] = String(apiKey); + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options: any = {}): FetchArgs { + // verify required parameter 'status' is not null or undefined + if (status === null || status === undefined) { + throw new RequiredError('status','Required parameter status was null or undefined when calling findPetsByStatus.'); + } + const localVarPath = `/pet/findByStatus`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + if (status) { + localVarQueryParameter['status'] = status.join(COLLECTION_FORMATS["csv"]); + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param {Array} tags Tags to filter by + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByTags(tags: Array, options: any = {}): FetchArgs { + // verify required parameter 'tags' is not null or undefined + if (tags === null || tags === undefined) { + throw new RequiredError('tags','Required parameter tags was null or undefined when calling findPetsByTags.'); + } + const localVarPath = `/pet/findByTags`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + if (tags) { + localVarQueryParameter['tags'] = tags.join(COLLECTION_FORMATS["csv"]); + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Returns a single pet + * @summary Find pet by ID + * @param {number} petId ID of pet to return + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getPetById(petId: number, options: any = {}): FetchArgs { + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError('petId','Required parameter petId was null or undefined when calling getPetById.'); + } + const localVarPath = `/pet/{petId}` + .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication api_key required + if (configuration && configuration.apiKey) { + const localVarApiKeyValue = typeof configuration.apiKey === 'function' + ? configuration.apiKey("api_key") + : configuration.apiKey; + localVarHeaderParameter["api_key"] = localVarApiKeyValue; + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Update an existing pet + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePet(body: Pet, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling updatePet.'); + } + const localVarPath = `/pet`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'PUT' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("Pet" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Updates a pet in the store with form data + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePetWithForm(petId: number, name?: string, status?: string, options: any = {}): FetchArgs { + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError('petId','Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + const localVarPath = `/pet/{petId}` + .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + const localVarFormParams = new url.URLSearchParams(); + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + if (name !== undefined) { + localVarFormParams.set('name', name as any); + } + + if (status !== undefined) { + localVarFormParams.set('status', status as any); + } + + localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = localVarFormParams.toString(); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary uploads an image + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + uploadFile(petId: number, additionalMetadata?: string, file?: any, options: any = {}): FetchArgs { + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError('petId','Required parameter petId was null or undefined when calling uploadFile.'); + } + const localVarPath = `/pet/{petId}/uploadImage` + .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + const localVarFormParams = new url.URLSearchParams(); + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + if (additionalMetadata !== undefined) { + localVarFormParams.set('additionalMetadata', additionalMetadata as any); + } + + if (file !== undefined) { + localVarFormParams.set('file', file as any); + } + + localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = localVarFormParams.toString(); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * PetApi - functional programming interface + * @export + */ +export const PetApiFp = function(configuration?: Configuration) { + return { + /** + * + * @summary Add a new pet to the store + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + addPet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).addPet(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Deletes a pet + * @param {number} petId Pet id to delete + * @param {string} [apiKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deletePet(petId: number, apiKey?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).deletePet(petId, apiKey, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise> { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByStatus(status, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param {Array} tags Tags to filter by + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByTags(tags: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise> { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByTags(tags, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Returns a single pet + * @summary Find pet by ID + * @param {number} petId ID of pet to return + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getPetById(petId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).getPetById(petId, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Update an existing pet + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePet(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Updates a pet in the store with form data + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePetWithForm(petId: number, name?: string, status?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePetWithForm(petId, name, status, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary uploads an image + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).uploadFile(petId, additionalMetadata, file, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + } +}; + +/** + * PetApi - factory interface + * @export + */ +export const PetApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { + return { + /** + * + * @summary Add a new pet to the store + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + addPet(body: Pet, options?: any) { + return PetApiFp(configuration).addPet(body, options)(fetch, basePath); + }, + /** + * + * @summary Deletes a pet + * @param {number} petId Pet id to delete + * @param {string} [apiKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deletePet(petId: number, apiKey?: string, options?: any) { + return PetApiFp(configuration).deletePet(petId, apiKey, options)(fetch, basePath); + }, + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any) { + return PetApiFp(configuration).findPetsByStatus(status, options)(fetch, basePath); + }, + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param {Array} tags Tags to filter by + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByTags(tags: Array, options?: any) { + return PetApiFp(configuration).findPetsByTags(tags, options)(fetch, basePath); + }, + /** + * Returns a single pet + * @summary Find pet by ID + * @param {number} petId ID of pet to return + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getPetById(petId: number, options?: any) { + return PetApiFp(configuration).getPetById(petId, options)(fetch, basePath); + }, + /** + * + * @summary Update an existing pet + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePet(body: Pet, options?: any) { + return PetApiFp(configuration).updatePet(body, options)(fetch, basePath); + }, + /** + * + * @summary Updates a pet in the store with form data + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePetWithForm(petId: number, name?: string, status?: string, options?: any) { + return PetApiFp(configuration).updatePetWithForm(petId, name, status, options)(fetch, basePath); + }, + /** + * + * @summary uploads an image + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any) { + return PetApiFp(configuration).uploadFile(petId, additionalMetadata, file, options)(fetch, basePath); + }, + }; +}; + +/** + * PetApi - interface + * @export + * @interface PetApi + */ +export interface PetApiInterface { + /** + * + * @summary Add a new pet to the store + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApiInterface + */ + addPet(body: Pet, options?: any): Promise<{}>; + + /** + * + * @summary Deletes a pet + * @param {number} petId Pet id to delete + * @param {string} [apiKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApiInterface + */ + deletePet(petId: number, apiKey?: string, options?: any): Promise<{}>; + + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApiInterface + */ + findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any): Promise>; + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param {Array} tags Tags to filter by + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApiInterface + */ + findPetsByTags(tags: Array, options?: any): Promise>; + + /** + * Returns a single pet + * @summary Find pet by ID + * @param {number} petId ID of pet to return + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApiInterface + */ + getPetById(petId: number, options?: any): Promise; + + /** + * + * @summary Update an existing pet + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApiInterface + */ + updatePet(body: Pet, options?: any): Promise<{}>; + + /** + * + * @summary Updates a pet in the store with form data + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApiInterface + */ + updatePetWithForm(petId: number, name?: string, status?: string, options?: any): Promise<{}>; + + /** + * + * @summary uploads an image + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApiInterface + */ + uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): Promise; + +} + +/** + * PetApi - object-oriented interface + * @export + * @class PetApi + * @extends {BaseAPI} + */ +export class PetApi extends BaseAPI implements PetApiInterface { + /** + * + * @summary Add a new pet to the store + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public addPet(body: Pet, options?: any) { + return PetApiFp(this.configuration).addPet(body, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Deletes a pet + * @param {number} petId Pet id to delete + * @param {string} [apiKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public deletePet(petId: number, apiKey?: string, options?: any) { + return PetApiFp(this.configuration).deletePet(petId, apiKey, options)(this.fetch, this.basePath); + } + + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any) { + return PetApiFp(this.configuration).findPetsByStatus(status, options)(this.fetch, this.basePath); + } + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param {Array} tags Tags to filter by + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public findPetsByTags(tags: Array, options?: any) { + return PetApiFp(this.configuration).findPetsByTags(tags, options)(this.fetch, this.basePath); + } + + /** + * Returns a single pet + * @summary Find pet by ID + * @param {number} petId ID of pet to return + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public getPetById(petId: number, options?: any) { + return PetApiFp(this.configuration).getPetById(petId, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Update an existing pet + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public updatePet(body: Pet, options?: any) { + return PetApiFp(this.configuration).updatePet(body, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Updates a pet in the store with form data + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public updatePetWithForm(petId: number, name?: string, status?: string, options?: any) { + return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options)(this.fetch, this.basePath); + } + + /** + * + * @summary uploads an image + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any) { + return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options)(this.fetch, this.basePath); + } + +} + +/** + * StoreApi - fetch parameter creator + * @export + */ +export const StoreApiFetchParamCreator = function (configuration?: Configuration) { + return { + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @summary Delete purchase order by ID + * @param {string} orderId ID of the order that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteOrder(orderId: string, options: any = {}): FetchArgs { + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new RequiredError('orderId','Required parameter orderId was null or undefined when calling deleteOrder.'); + } + const localVarPath = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, encodeURIComponent(String(orderId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getInventory(options: any = {}): FetchArgs { + const localVarPath = `/store/inventory`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication api_key required + if (configuration && configuration.apiKey) { + const localVarApiKeyValue = typeof configuration.apiKey === 'function' + ? configuration.apiKey("api_key") + : configuration.apiKey; + localVarHeaderParameter["api_key"] = localVarApiKeyValue; + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param {number} orderId ID of pet that needs to be fetched + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getOrderById(orderId: number, options: any = {}): FetchArgs { + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new RequiredError('orderId','Required parameter orderId was null or undefined when calling getOrderById.'); + } + const localVarPath = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, encodeURIComponent(String(orderId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Place an order for a pet + * @param {Order} body order placed for purchasing the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + placeOrder(body: Order, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling placeOrder.'); + } + const localVarPath = `/store/order`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("Order" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * StoreApi - functional programming interface + * @export + */ +export const StoreApiFp = function(configuration?: Configuration) { + return { + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @summary Delete purchase order by ID + * @param {string} orderId ID of the order that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteOrder(orderId: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).deleteOrder(orderId, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getInventory(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getInventory(options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param {number} orderId ID of pet that needs to be fetched + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getOrderById(orderId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getOrderById(orderId, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Place an order for a pet + * @param {Order} body order placed for purchasing the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + placeOrder(body: Order, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).placeOrder(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + } +}; + +/** + * StoreApi - factory interface + * @export + */ +export const StoreApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { + return { + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @summary Delete purchase order by ID + * @param {string} orderId ID of the order that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteOrder(orderId: string, options?: any) { + return StoreApiFp(configuration).deleteOrder(orderId, options)(fetch, basePath); + }, + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getInventory(options?: any) { + return StoreApiFp(configuration).getInventory(options)(fetch, basePath); + }, + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param {number} orderId ID of pet that needs to be fetched + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getOrderById(orderId: number, options?: any) { + return StoreApiFp(configuration).getOrderById(orderId, options)(fetch, basePath); + }, + /** + * + * @summary Place an order for a pet + * @param {Order} body order placed for purchasing the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + placeOrder(body: Order, options?: any) { + return StoreApiFp(configuration).placeOrder(body, options)(fetch, basePath); + }, + }; +}; + +/** + * StoreApi - interface + * @export + * @interface StoreApi + */ +export interface StoreApiInterface { + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @summary Delete purchase order by ID + * @param {string} orderId ID of the order that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApiInterface + */ + deleteOrder(orderId: string, options?: any): Promise<{}>; + + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApiInterface + */ + getInventory(options?: any): Promise<{ [key: string]: number; }>; + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param {number} orderId ID of pet that needs to be fetched + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApiInterface + */ + getOrderById(orderId: number, options?: any): Promise; + + /** + * + * @summary Place an order for a pet + * @param {Order} body order placed for purchasing the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApiInterface + */ + placeOrder(body: Order, options?: any): Promise; + +} + +/** + * StoreApi - object-oriented interface + * @export + * @class StoreApi + * @extends {BaseAPI} + */ +export class StoreApi extends BaseAPI implements StoreApiInterface { + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @summary Delete purchase order by ID + * @param {string} orderId ID of the order that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApi + */ + public deleteOrder(orderId: string, options?: any) { + return StoreApiFp(this.configuration).deleteOrder(orderId, options)(this.fetch, this.basePath); + } + + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApi + */ + public getInventory(options?: any) { + return StoreApiFp(this.configuration).getInventory(options)(this.fetch, this.basePath); + } + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param {number} orderId ID of pet that needs to be fetched + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApi + */ + public getOrderById(orderId: number, options?: any) { + return StoreApiFp(this.configuration).getOrderById(orderId, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Place an order for a pet + * @param {Order} body order placed for purchasing the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApi + */ + public placeOrder(body: Order, options?: any) { + return StoreApiFp(this.configuration).placeOrder(body, options)(this.fetch, this.basePath); + } + +} + +/** + * UserApi - fetch parameter creator + * @export + */ +export const UserApiFetchParamCreator = function (configuration?: Configuration) { + return { + /** + * This can only be done by the logged in user. + * @summary Create user + * @param {User} body Created user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUser(body: User, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling createUser.'); + } + const localVarPath = `/user`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("User" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithArrayInput(body: Array, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + const localVarPath = `/user/createWithArray`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("Array<User>" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithListInput(body: Array, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + const localVarPath = `/user/createWithList`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("Array<User>" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param {string} username The name that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteUser(username: string, options: any = {}): FetchArgs { + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new RequiredError('username','Required parameter username was null or undefined when calling deleteUser.'); + } + const localVarPath = `/user/{username}` + .replace(`{${"username"}}`, encodeURIComponent(String(username))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Get user by user name + * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getUserByName(username: string, options: any = {}): FetchArgs { + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new RequiredError('username','Required parameter username was null or undefined when calling getUserByName.'); + } + const localVarPath = `/user/{username}` + .replace(`{${"username"}}`, encodeURIComponent(String(username))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Logs user into the system + * @param {string} username The user name for login + * @param {string} password The password for login in clear text + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + loginUser(username: string, password: string, options: any = {}): FetchArgs { + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new RequiredError('username','Required parameter username was null or undefined when calling loginUser.'); + } + // verify required parameter 'password' is not null or undefined + if (password === null || password === undefined) { + throw new RequiredError('password','Required parameter password was null or undefined when calling loginUser.'); + } + const localVarPath = `/user/login`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (username !== undefined) { + localVarQueryParameter['username'] = username; + } + + if (password !== undefined) { + localVarQueryParameter['password'] = password; + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Logs out current logged in user session + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + logoutUser(options: any = {}): FetchArgs { + const localVarPath = `/user/logout`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param {string} username name that need to be deleted + * @param {User} body Updated user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updateUser(username: string, body: User, options: any = {}): FetchArgs { + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new RequiredError('username','Required parameter username was null or undefined when calling updateUser.'); + } + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling updateUser.'); + } + const localVarPath = `/user/{username}` + .replace(`{${"username"}}`, encodeURIComponent(String(username))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'PUT' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("User" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * UserApi - functional programming interface + * @export + */ +export const UserApiFp = function(configuration?: Configuration) { + return { + /** + * This can only be done by the logged in user. + * @summary Create user + * @param {User} body Created user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUser(body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUser(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithArrayInput(body: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithArrayInput(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithListInput(body: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithListInput(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param {string} username The name that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteUser(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).deleteUser(username, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Get user by user name + * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getUserByName(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).getUserByName(username, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Logs user into the system + * @param {string} username The user name for login + * @param {string} password The password for login in clear text + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + loginUser(username: string, password: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).loginUser(username, password, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Logs out current logged in user session + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + logoutUser(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).logoutUser(options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param {string} username name that need to be deleted + * @param {User} body Updated user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updateUser(username: string, body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).updateUser(username, body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + } +}; + +/** + * UserApi - factory interface + * @export + */ +export const UserApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { + return { + /** + * This can only be done by the logged in user. + * @summary Create user + * @param {User} body Created user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUser(body: User, options?: any) { + return UserApiFp(configuration).createUser(body, options)(fetch, basePath); + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithArrayInput(body: Array, options?: any) { + return UserApiFp(configuration).createUsersWithArrayInput(body, options)(fetch, basePath); + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithListInput(body: Array, options?: any) { + return UserApiFp(configuration).createUsersWithListInput(body, options)(fetch, basePath); + }, + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param {string} username The name that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteUser(username: string, options?: any) { + return UserApiFp(configuration).deleteUser(username, options)(fetch, basePath); + }, + /** + * + * @summary Get user by user name + * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getUserByName(username: string, options?: any) { + return UserApiFp(configuration).getUserByName(username, options)(fetch, basePath); + }, + /** + * + * @summary Logs user into the system + * @param {string} username The user name for login + * @param {string} password The password for login in clear text + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + loginUser(username: string, password: string, options?: any) { + return UserApiFp(configuration).loginUser(username, password, options)(fetch, basePath); + }, + /** + * + * @summary Logs out current logged in user session + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + logoutUser(options?: any) { + return UserApiFp(configuration).logoutUser(options)(fetch, basePath); + }, + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param {string} username name that need to be deleted + * @param {User} body Updated user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updateUser(username: string, body: User, options?: any) { + return UserApiFp(configuration).updateUser(username, body, options)(fetch, basePath); + }, + }; +}; + +/** + * UserApi - interface + * @export + * @interface UserApi + */ +export interface UserApiInterface { + /** + * This can only be done by the logged in user. + * @summary Create user + * @param {User} body Created user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApiInterface + */ + createUser(body: User, options?: any): Promise<{}>; + + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApiInterface + */ + createUsersWithArrayInput(body: Array, options?: any): Promise<{}>; + + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApiInterface + */ + createUsersWithListInput(body: Array, options?: any): Promise<{}>; + + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param {string} username The name that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApiInterface + */ + deleteUser(username: string, options?: any): Promise<{}>; + + /** + * + * @summary Get user by user name + * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApiInterface + */ + getUserByName(username: string, options?: any): Promise; + + /** + * + * @summary Logs user into the system + * @param {string} username The user name for login + * @param {string} password The password for login in clear text + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApiInterface + */ + loginUser(username: string, password: string, options?: any): Promise; + + /** + * + * @summary Logs out current logged in user session + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApiInterface + */ + logoutUser(options?: any): Promise<{}>; + + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param {string} username name that need to be deleted + * @param {User} body Updated user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApiInterface + */ + updateUser(username: string, body: User, options?: any): Promise<{}>; + +} + +/** + * UserApi - object-oriented interface + * @export + * @class UserApi + * @extends {BaseAPI} + */ +export class UserApi extends BaseAPI implements UserApiInterface { + /** + * This can only be done by the logged in user. + * @summary Create user + * @param {User} body Created user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public createUser(body: User, options?: any) { + return UserApiFp(this.configuration).createUser(body, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public createUsersWithArrayInput(body: Array, options?: any) { + return UserApiFp(this.configuration).createUsersWithArrayInput(body, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public createUsersWithListInput(body: Array, options?: any) { + return UserApiFp(this.configuration).createUsersWithListInput(body, options)(this.fetch, this.basePath); + } + + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param {string} username The name that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public deleteUser(username: string, options?: any) { + return UserApiFp(this.configuration).deleteUser(username, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Get user by user name + * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public getUserByName(username: string, options?: any) { + return UserApiFp(this.configuration).getUserByName(username, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Logs user into the system + * @param {string} username The user name for login + * @param {string} password The password for login in clear text + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public loginUser(username: string, password: string, options?: any) { + return UserApiFp(this.configuration).loginUser(username, password, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Logs out current logged in user session + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public logoutUser(options?: any) { + return UserApiFp(this.configuration).logoutUser(options)(this.fetch, this.basePath); + } + + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param {string} username name that need to be deleted + * @param {User} body Updated user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public updateUser(username: string, body: User, options?: any) { + return UserApiFp(this.configuration).updateUser(username, body, options)(this.fetch, this.basePath); + } + +} + diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/configuration.ts b/samples/client/petstore/typescript-fetch/builds/with-interfaces/configuration.ts new file mode 100644 index 000000000000..ca7b7e641b51 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/configuration.ts @@ -0,0 +1,66 @@ +// tslint:disable +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface ConfigurationParameters { + apiKey?: string | ((name: string) => string); + username?: string; + password?: string; + accessToken?: string | ((name: string, scopes?: string[]) => string); + basePath?: string; +} + +export class Configuration { + /** + * parameter for apiKey security + * @param name security name + * @memberof Configuration + */ + apiKey?: string | ((name: string) => string); + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + username?: string; + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + password?: string; + /** + * parameter for oauth2 security + * @param name security name + * @param scopes oauth2 scope + * @memberof Configuration + */ + accessToken?: string | ((name: string, scopes?: string[]) => string); + /** + * override base path + * + * @type {string} + * @memberof Configuration + */ + basePath?: string; + + constructor(param: ConfigurationParameters = {}) { + this.apiKey = param.apiKey; + this.username = param.username; + this.password = param.password; + this.accessToken = param.accessToken; + this.basePath = param.basePath; + } +} diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/custom.d.ts b/samples/client/petstore/typescript-fetch/builds/with-interfaces/custom.d.ts new file mode 100644 index 000000000000..9a5ceb3588a8 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/custom.d.ts @@ -0,0 +1,2 @@ +declare module 'portable-fetch'; +declare module 'url'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/git_push.sh b/samples/client/petstore/typescript-fetch/builds/with-interfaces/git_push.sh new file mode 100644 index 000000000000..a1ff4c9bcba8 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/git_push.sh @@ -0,0 +1,51 @@ +#!/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 swagger-petstore-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/typescript-fetch/builds/with-interfaces/index.ts b/samples/client/petstore/typescript-fetch/builds/with-interfaces/index.ts new file mode 100644 index 000000000000..052a883aaaa9 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/index.ts @@ -0,0 +1,16 @@ +// tslint:disable +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export * from "./api"; +export * from "./configuration"; diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts index 72e705621fa2..7b89d8a61f52 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -210,13 +210,13 @@ export interface Pet { name: string; /** * - * @type {Array<string>} + * @type {Array} * @memberof Pet */ photoUrls: Array; /** * - * @type {Array<Tag>} + * @type {Array} * @memberof Pet */ tags?: Array; @@ -414,7 +414,7 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -455,7 +455,7 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {Array<string>} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -726,7 +726,7 @@ export const PetApiFp = function(configuration?: Configuration) { /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -745,7 +745,7 @@ export const PetApiFp = function(configuration?: Configuration) { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {Array<string>} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -874,7 +874,7 @@ export const PetApiFactory = function (configuration?: Configuration, fetch?: Fe /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -884,7 +884,7 @@ export const PetApiFactory = function (configuration?: Configuration, fetch?: Fe /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {Array<string>} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -948,7 +948,7 @@ export class PetApi extends BaseAPI { /** * * @summary Add a new pet to the store - * @param {} body Pet object that needs to be added to the store + * @param {Pet} body Pet object that needs to be added to the store * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -960,8 +960,8 @@ export class PetApi extends BaseAPI { /** * * @summary Deletes a pet - * @param {} petId Pet id to delete - * @param {} [apiKey] + * @param {number} petId Pet id to delete + * @param {string} [apiKey] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -973,7 +973,7 @@ export class PetApi extends BaseAPI { /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status - * @param {} status Status values that need to be considered for filter + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -985,7 +985,7 @@ export class PetApi extends BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags - * @param {} tags Tags to filter by + * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -997,7 +997,7 @@ export class PetApi extends BaseAPI { /** * Returns a single pet * @summary Find pet by ID - * @param {} petId ID of pet to return + * @param {number} petId ID of pet to return * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1009,7 +1009,7 @@ export class PetApi extends BaseAPI { /** * * @summary Update an existing pet - * @param {} body Pet object that needs to be added to the store + * @param {Pet} body Pet object that needs to be added to the store * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1021,9 +1021,9 @@ export class PetApi extends BaseAPI { /** * * @summary Updates a pet in the store with form data - * @param {} petId ID of pet that needs to be updated - * @param {} [name] Updated name of the pet - * @param {} [status] Updated status of the pet + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1035,9 +1035,9 @@ export class PetApi extends BaseAPI { /** * * @summary uploads an image - * @param {} petId ID of pet to update - * @param {} [additionalMetadata] Additional data to pass to server - * @param {} [file] file to upload + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi @@ -1320,7 +1320,7 @@ export class StoreApi extends BaseAPI { /** * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @summary Delete purchase order by ID - * @param {} orderId ID of the order that needs to be deleted + * @param {string} orderId ID of the order that needs to be deleted * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StoreApi @@ -1343,7 +1343,7 @@ export class StoreApi extends BaseAPI { /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @summary Find purchase order by ID - * @param {} orderId ID of pet that needs to be fetched + * @param {number} orderId ID of pet that needs to be fetched * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StoreApi @@ -1355,7 +1355,7 @@ export class StoreApi extends BaseAPI { /** * * @summary Place an order for a pet - * @param {} body order placed for purchasing the pet + * @param {Order} body order placed for purchasing the pet * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StoreApi @@ -1407,7 +1407,7 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1439,7 +1439,7 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1500,7 +1500,7 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) /** * * @summary Get user by user name - * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1659,7 +1659,7 @@ export const UserApiFp = function(configuration?: Configuration) { /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1678,7 +1678,7 @@ export const UserApiFp = function(configuration?: Configuration) { /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1716,7 +1716,7 @@ export const UserApiFp = function(configuration?: Configuration) { /** * * @summary Get user by user name - * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1812,7 +1812,7 @@ export const UserApiFactory = function (configuration?: Configuration, fetch?: F /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1822,7 +1822,7 @@ export const UserApiFactory = function (configuration?: Configuration, fetch?: F /** * * @summary Creates list of users with given input array - * @param {Array<User>} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1842,7 +1842,7 @@ export const UserApiFactory = function (configuration?: Configuration, fetch?: F /** * * @summary Get user by user name - * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1893,7 +1893,7 @@ export class UserApi extends BaseAPI { /** * This can only be done by the logged in user. * @summary Create user - * @param {} body Created user object + * @param {User} body Created user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1905,7 +1905,7 @@ export class UserApi extends BaseAPI { /** * * @summary Creates list of users with given input array - * @param {} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1917,7 +1917,7 @@ export class UserApi extends BaseAPI { /** * * @summary Creates list of users with given input array - * @param {} body List of user object + * @param {Array} body List of user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1929,7 +1929,7 @@ export class UserApi extends BaseAPI { /** * This can only be done by the logged in user. * @summary Delete user - * @param {} username The name that needs to be deleted + * @param {string} username The name that needs to be deleted * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1941,7 +1941,7 @@ export class UserApi extends BaseAPI { /** * * @summary Get user by user name - * @param {} username The name that needs to be fetched. Use user1 for testing. + * @param {string} username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1953,8 +1953,8 @@ export class UserApi extends BaseAPI { /** * * @summary Logs user into the system - * @param {} username The user name for login - * @param {} password The password for login in clear text + * @param {string} username The user name for login + * @param {string} password The password for login in clear text * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi @@ -1977,8 +1977,8 @@ export class UserApi extends BaseAPI { /** * This can only be done by the logged in user. * @summary Updated user - * @param {} username name that need to be deleted - * @param {} body Updated user object + * @param {string} username name that need to be deleted + * @param {User} body Updated user object * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi diff --git a/samples/client/petstore/typescript-inversify/.swagger-codegen-ignore b/samples/client/petstore/typescript-inversify/.swagger-codegen-ignore new file mode 100644 index 000000000000..c5fa491b4c55 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/typescript-inversify/.swagger-codegen/VERSION b/samples/client/petstore/typescript-inversify/.swagger-codegen/VERSION new file mode 100644 index 000000000000..855ff9501eb8 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-inversify/ApiServiceBinder.ts b/samples/client/petstore/typescript-inversify/ApiServiceBinder.ts new file mode 100644 index 000000000000..779a08712085 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/ApiServiceBinder.ts @@ -0,0 +1,13 @@ +import {interfaces} from "inversify"; + +import { PetService } from './api/pet.service'; +import { StoreService } from './api/store.service'; +import { UserService } from './api/user.service'; + +export class ApiServiceBinder { + public static with(container: interfaces.Container) { + container.bind("PetService").to(PetService).inSingletonScope(); + container.bind("StoreService").to(StoreService).inSingletonScope(); + container.bind("UserService").to(UserService).inSingletonScope(); + } +} diff --git a/samples/client/petstore/typescript-inversify/Headers.ts b/samples/client/petstore/typescript-inversify/Headers.ts new file mode 100644 index 000000000000..0fa7760e01ea --- /dev/null +++ b/samples/client/petstore/typescript-inversify/Headers.ts @@ -0,0 +1,3 @@ +export interface Headers { + [index:string]: string +} diff --git a/samples/client/petstore/typescript-inversify/HttpClient.ts b/samples/client/petstore/typescript-inversify/HttpClient.ts new file mode 100644 index 000000000000..64fe12a30452 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/HttpClient.ts @@ -0,0 +1,63 @@ +import IHttpClient from "./IHttpClient"; +import { Observable } from "rxjs/Observable"; +import "whatwg-fetch"; +import HttpResponse from "./HttpResponse"; +import {injectable} from "inversify"; +import "rxjs/add/observable/fromPromise"; +import { Headers } from "./Headers"; + +@injectable() +class HttpClient implements IHttpClient { + + get(url:string, headers?: Headers):Observable { + return this.performNetworkCall(url, "get", undefined, headers); + } + + post(url: string, body: {}|FormData, headers?: Headers): Observable { + return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + put(url: string, body: {}, headers?: Headers): Observable { + return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + delete(url: string, headers?: Headers): Observable { + return this.performNetworkCall(url, "delete", undefined, headers); + } + + private getJsonBody(body: {}|FormData) { + return !(body instanceof FormData) ? JSON.stringify(body) : body; + } + + private addJsonHeaders(headers: Headers) { + return Object.assign({}, { + "Accept": "application/json", + "Content-Type": "application/json" + }, headers); + }; + + private performNetworkCall(url: string, method: string, body?: any, headers?: Headers): Observable { + let promise = window.fetch(url, { + method: method, + body: body, + headers: headers + }).then(response => { + let headers: Headers = {}; + response.headers.forEach((value, name) => { + headers[name.toString().toLowerCase()] = value; + }); + return response.text().then(text => { + let contentType = headers["content-type"] || ""; + let payload = contentType.match("application/json") ? JSON.parse(text) : text; + let httpResponse = new HttpResponse(payload, response.status, headers); + + if (response.status >= 400) + throw httpResponse; + return httpResponse; + }); + }); + return Observable.fromPromise(promise); + } +} + +export default HttpClient \ No newline at end of file diff --git a/samples/client/petstore/typescript-inversify/HttpResponse.ts b/samples/client/petstore/typescript-inversify/HttpResponse.ts new file mode 100644 index 000000000000..411240cde2bd --- /dev/null +++ b/samples/client/petstore/typescript-inversify/HttpResponse.ts @@ -0,0 +1,8 @@ +import { Headers } from "./Headers" + +class HttpResponse { + constructor(public response: T, public status:number, public headers?: Headers) { + } +} + +export default HttpResponse \ No newline at end of file diff --git a/samples/client/petstore/typescript-inversify/IAPIConfiguration.ts b/samples/client/petstore/typescript-inversify/IAPIConfiguration.ts new file mode 100644 index 000000000000..2364e83e6cb3 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/IAPIConfiguration.ts @@ -0,0 +1,8 @@ +export interface IAPIConfiguration { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-inversify/IHttpClient.ts b/samples/client/petstore/typescript-inversify/IHttpClient.ts new file mode 100644 index 000000000000..22d9e07c903e --- /dev/null +++ b/samples/client/petstore/typescript-inversify/IHttpClient.ts @@ -0,0 +1,12 @@ +import { Observable } from "rxjs/Observable"; +import HttpResponse from "./HttpResponse"; +import { Headers } from "./Headers"; + +interface IHttpClient { + get(url:string, headers?: Headers):Observable + post(url:string, body:{}|FormData, headers?: Headers):Observable + put(url:string, body:{}, headers?: Headers):Observable + delete(url:string, headers?: Headers):Observable +} + +export default IHttpClient \ No newline at end of file diff --git a/samples/client/petstore/typescript-inversify/api/pet.service.ts b/samples/client/petstore/typescript-inversify/api/pet.service.ts new file mode 100644 index 000000000000..b52d0f56cf83 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/api/pet.service.ts @@ -0,0 +1,315 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Observable } from "rxjs/Observable"; +import 'rxjs/add/operator/map'; +import 'rxjs/add/operator/toPromise'; +import IHttpClient from "../IHttpClient"; +import { inject, injectable } from "inversify"; +import { IAPIConfiguration } from "../IAPIConfiguration"; +import { Headers } from "../Headers"; +import HttpResponse from "../HttpResponse"; + +import { ApiResponse } from '../model/apiResponse'; +import { Pet } from '../model/pet'; + +import { COLLECTION_FORMATS } from '../variables'; + + + +@injectable() +export class PetService { + private basePath: string = 'http://petstore.swagger.io/v2'; + + constructor(@inject("IApiHttpClient") private httpClient: IHttpClient, + @inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) { + if(this.APIConfiguration.basePath) + this.basePath = this.APIConfiguration.basePath; + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + + */ + public addPet(body: Pet, observe?: 'body', headers?: Headers): Observable; + public addPet(body: Pet, observe?: 'response', headers?: Headers): Observable>; + public addPet(body: Pet, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling addPet.'); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.post(`${this.basePath}/pet`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + + */ + public deletePet(petId: number, apiKey?: string, observe?: 'body', headers?: Headers): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', headers?: Headers): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!petId){ + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + if (apiKey) { + headers['api_key'] = String(apiKey); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.delete(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * 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 + + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', headers?: Headers): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', headers?: Headers): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', headers: Headers = {}): Observable { + if (!status){ + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + let queryParameters: string[] = []; + if (status) { + queryParameters.push("status="+encodeURIComponent(status.join(COLLECTION_FORMATS['csv']))); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + + const response: Observable>> = this.httpClient.get(`${this.basePath}/pet/findByStatus?${queryParameters.join('&')}`, headers); + if (observe == 'body') { + return response.map(httpResponse => >(httpResponse.response)); + } + return response; + } + + + /** + * 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 + + */ + public findPetsByTags(tags: Array, observe?: 'body', headers?: Headers): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', headers?: Headers): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', headers: Headers = {}): Observable { + if (!tags){ + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + let queryParameters: string[] = []; + if (tags) { + queryParameters.push("tags="+encodeURIComponent(tags.join(COLLECTION_FORMATS['csv']))); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + + const response: Observable>> = this.httpClient.get(`${this.basePath}/pet/findByTags?${queryParameters.join('&')}`, headers); + if (observe == 'body') { + return response.map(httpResponse => >(httpResponse.response)); + } + return response; + } + + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + + */ + public getPetById(petId: number, observe?: 'body', headers?: Headers): Observable; + public getPetById(petId: number, observe?: 'response', headers?: Headers): Observable>; + public getPetById(petId: number, observe: any = 'body', headers: Headers = {}): Observable { + if (!petId){ + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + // authentication (api_key) required + if (this.APIConfiguration.apiKeys["api_key"]) { + headers['api_key'] = this.APIConfiguration.apiKeys["api_key"]; + } + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + + */ + public updatePet(body: Pet, observe?: 'body', headers?: Headers): Observable; + public updatePet(body: Pet, observe?: 'response', headers?: Headers): Observable>; + public updatePet(body: Pet, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling updatePet.'); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.put(`${this.basePath}/pet`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + + */ + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', headers?: Headers): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', headers?: Headers): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!petId){ + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + + let formData: FormData = new FormData(); + headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; + if (name !== undefined) { + formData.append('name', name); + } + if (status !== undefined) { + formData.append('status', status); + } + + const response: Observable> = this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, body, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', headers?: Headers): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', headers?: Headers): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', headers: Headers = {}): Observable { + if (!petId){ + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/json'; + + let formData: FormData = new FormData(); + headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; + if (additionalMetadata !== undefined) { + formData.append('additionalMetadata', additionalMetadata); + } + if (file !== undefined) { + formData.append('file', file); + } + + const response: Observable> = this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, body, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + +} diff --git a/samples/client/petstore/typescript-inversify/api/store.service.ts b/samples/client/petstore/typescript-inversify/api/store.service.ts new file mode 100644 index 000000000000..0185d32f2af2 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/api/store.service.ts @@ -0,0 +1,130 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Observable } from "rxjs/Observable"; +import 'rxjs/add/operator/map'; +import 'rxjs/add/operator/toPromise'; +import IHttpClient from "../IHttpClient"; +import { inject, injectable } from "inversify"; +import { IAPIConfiguration } from "../IAPIConfiguration"; +import { Headers } from "../Headers"; +import HttpResponse from "../HttpResponse"; + +import { Order } from '../model/order'; + +import { COLLECTION_FORMATS } from '../variables'; + + + +@injectable() +export class StoreService { + private basePath: string = 'http://petstore.swagger.io/v2'; + + constructor(@inject("IApiHttpClient") private httpClient: IHttpClient, + @inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) { + if(this.APIConfiguration.basePath) + this.basePath = this.APIConfiguration.basePath; + } + + /** + * 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 + + */ + public deleteOrder(orderId: string, observe?: 'body', headers?: Headers): Observable; + public deleteOrder(orderId: string, observe?: 'response', headers?: Headers): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!orderId){ + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.delete(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + + */ + public getInventory(observe?: 'body', headers?: Headers): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', headers?: Headers): Observable>; + public getInventory(observe: any = 'body', headers: Headers = {}): Observable { + // authentication (api_key) required + if (this.APIConfiguration.apiKeys["api_key"]) { + headers['api_key'] = this.APIConfiguration.apiKeys["api_key"]; + } + headers['Accept'] = 'application/json'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/store/inventory`, headers); + if (observe == 'body') { + return response.map(httpResponse => <{ [key: string]: number; }>(httpResponse.response)); + } + return response; + } + + + /** + * 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 + + */ + public getOrderById(orderId: number, observe?: 'body', headers?: Headers): Observable; + public getOrderById(orderId: number, observe?: 'response', headers?: Headers): Observable>; + public getOrderById(orderId: number, observe: any = 'body', headers: Headers = {}): Observable { + if (!orderId){ + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + + */ + public placeOrder(body: Order, observe?: 'body', headers?: Headers): Observable; + public placeOrder(body: Order, observe?: 'response', headers?: Headers): Observable>; + public placeOrder(body: Order, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling placeOrder.'); + } + + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.post(`${this.basePath}/store/order`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + +} diff --git a/samples/client/petstore/typescript-inversify/api/user.service.ts b/samples/client/petstore/typescript-inversify/api/user.service.ts new file mode 100644 index 000000000000..3a794603bf87 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/api/user.service.ts @@ -0,0 +1,239 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Observable } from "rxjs/Observable"; +import 'rxjs/add/operator/map'; +import 'rxjs/add/operator/toPromise'; +import IHttpClient from "../IHttpClient"; +import { inject, injectable } from "inversify"; +import { IAPIConfiguration } from "../IAPIConfiguration"; +import { Headers } from "../Headers"; +import HttpResponse from "../HttpResponse"; + +import { User } from '../model/user'; + +import { COLLECTION_FORMATS } from '../variables'; + + + +@injectable() +export class UserService { + private basePath: string = 'http://petstore.swagger.io/v2'; + + constructor(@inject("IApiHttpClient") private httpClient: IHttpClient, + @inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) { + if(this.APIConfiguration.basePath) + this.basePath = this.APIConfiguration.basePath; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + + */ + public createUser(body: User, observe?: 'body', headers?: Headers): Observable; + public createUser(body: User, observe?: 'response', headers?: Headers): Observable>; + public createUser(body: User, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling createUser.'); + } + + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.post(`${this.basePath}/user`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Creates list of users with given input array + * + * @param body List of user object + + */ + public createUsersWithArrayInput(body: Array, observe?: 'body', headers?: Headers): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', headers?: Headers): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.post(`${this.basePath}/user/createWithArray`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Creates list of users with given input array + * + * @param body List of user object + + */ + public createUsersWithListInput(body: Array, observe?: 'body', headers?: Headers): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', headers?: Headers): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.post(`${this.basePath}/user/createWithList`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + + */ + public deleteUser(username: string, observe?: 'body', headers?: Headers): Observable; + public deleteUser(username: string, observe?: 'response', headers?: Headers): Observable>; + public deleteUser(username: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!username){ + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.delete(`${this.basePath}/user/${encodeURIComponent(String(username))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + + */ + public getUserByName(username: string, observe?: 'body', headers?: Headers): Observable; + public getUserByName(username: string, observe?: 'response', headers?: Headers): Observable>; + public getUserByName(username: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!username){ + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/user/${encodeURIComponent(String(username))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + + */ + public loginUser(username: string, password: string, observe?: 'body', headers?: Headers): Observable; + public loginUser(username: string, password: string, observe?: 'response', headers?: Headers): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!username){ + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + + if (!password){ + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let queryParameters: string[] = []; + if (username !== undefined) { + queryParameters.push("username="+encodeURIComponent(String(username))); + } + if (password !== undefined) { + queryParameters.push("password="+encodeURIComponent(String(password))); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/user/login?${queryParameters.join('&')}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Logs out current logged in user session + * + + */ + public logoutUser(observe?: 'body', headers?: Headers): Observable; + public logoutUser(observe?: 'response', headers?: Headers): Observable>; + public logoutUser(observe: any = 'body', headers: Headers = {}): Observable { + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/user/logout`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + + */ + public updateUser(username: string, body: User, observe?: 'body', headers?: Headers): Observable; + public updateUser(username: string, body: User, observe?: 'response', headers?: Headers): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', headers: Headers = {}): Observable { + if (!username){ + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + + if (!body){ + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.put(`${this.basePath}/user/${encodeURIComponent(String(username))}`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + +} diff --git a/samples/client/petstore/typescript-inversify/model/apiResponse.ts b/samples/client/petstore/typescript-inversify/model/apiResponse.ts new file mode 100644 index 000000000000..af5590c3d859 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/apiResponse.ts @@ -0,0 +1,21 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +/** + * Describes the result of uploading an image resource + */ +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} diff --git a/samples/client/petstore/typescript-inversify/model/category.ts b/samples/client/petstore/typescript-inversify/model/category.ts new file mode 100644 index 000000000000..093bd438a382 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/category.ts @@ -0,0 +1,20 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +/** + * A category for a pet + */ +export interface Category { + id?: number; + name?: string; +} diff --git a/samples/client/petstore/typescript-inversify/model/order.ts b/samples/client/petstore/typescript-inversify/model/order.ts new file mode 100644 index 000000000000..6a1e1fd6bcfd --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/order.ts @@ -0,0 +1,35 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +/** + * An order for a pets from the pet store + */ +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: Date; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + } +} diff --git a/samples/client/petstore/typescript-inversify/model/pet.ts b/samples/client/petstore/typescript-inversify/model/pet.ts new file mode 100644 index 000000000000..b8b659008af8 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/pet.ts @@ -0,0 +1,37 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +/** + * A pet for sale in the pet store + */ +export interface Pet { + id?: number; + category?: Category; + name: string; + photoUrls: Array; + tags?: Array; + /** + * pet status in the store + */ + status?: Pet.StatusEnum; +} +export namespace Pet { + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + } +} diff --git a/samples/client/petstore/typescript-inversify/model/tag.ts b/samples/client/petstore/typescript-inversify/model/tag.ts new file mode 100644 index 000000000000..e35232df6914 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/tag.ts @@ -0,0 +1,20 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +/** + * A tag for a pet + */ +export interface Tag { + id?: number; + name?: string; +} diff --git a/samples/client/petstore/typescript-inversify/model/user.ts b/samples/client/petstore/typescript-inversify/model/user.ts new file mode 100644 index 000000000000..e8788de129c7 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/user.ts @@ -0,0 +1,29 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +/** + * A User who is purchasing from the pet store + */ +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} diff --git a/samples/client/petstore/typescript-inversify/variables.ts b/samples/client/petstore/typescript-inversify/variables.ts new file mode 100644 index 000000000000..5d3805255c2e --- /dev/null +++ b/samples/client/petstore/typescript-inversify/variables.ts @@ -0,0 +1,6 @@ +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/petstore/typescript-node/default/.swagger-codegen/VERSION b/samples/client/petstore/typescript-node/default/.swagger-codegen/VERSION index a6254504e401..855ff9501eb8 100644 --- a/samples/client/petstore/typescript-node/default/.swagger-codegen/VERSION +++ b/samples/client/petstore/typescript-node/default/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.1 \ No newline at end of file +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/default/api.ts b/samples/client/petstore/typescript-node/default/api.ts index 1e75275a0669..2a41b799beaa 100644 --- a/samples/client/petstore/typescript-node/default/api.ts +++ b/samples/client/petstore/typescript-node/default/api.ts @@ -140,9 +140,9 @@ class ObjectSerializer { * Describes the result of uploading an image resource */ export class ApiResponse { - 'code': number; - 'type': string; - 'message': string; + 'code'?: number; + 'type'?: string; + 'message'?: string; static discriminator = undefined; @@ -172,8 +172,8 @@ export class ApiResponse { * A category for a pet */ export class Category { - 'id': number; - 'name': string; + 'id'?: number; + 'name'?: string; static discriminator = undefined; @@ -198,15 +198,15 @@ export class Category { * An order for a pets from the pet store */ export class Order { - 'id': number; - 'petId': number; - 'quantity': number; - 'shipDate': Date; + 'id'?: number; + 'petId'?: number; + 'quantity'?: number; + 'shipDate'?: Date; /** * Order Status */ - 'status': Order.StatusEnum; - 'complete': boolean; + 'status'?: Order.StatusEnum; + 'complete'?: boolean; static discriminator = undefined; @@ -258,15 +258,15 @@ export namespace Order { * A pet for sale in the pet store */ export class Pet { - 'id': number; - 'category': Category; + 'id'?: number; + 'category'?: Category; 'name': string; 'photoUrls': Array; - 'tags': Array; + 'tags'?: Array; /** * pet status in the store */ - 'status': Pet.StatusEnum; + 'status'?: Pet.StatusEnum; static discriminator = undefined; @@ -318,8 +318,8 @@ export namespace Pet { * A tag for a pet */ export class Tag { - 'id': number; - 'name': string; + 'id'?: number; + 'name'?: string; static discriminator = undefined; @@ -344,17 +344,17 @@ export class Tag { * A User who is purchasing from the pet store */ export class User { - 'id': number; - 'username': string; - 'firstName': string; - 'lastName': string; - 'email': string; - 'password': string; - 'phone': string; + 'id'?: number; + 'username'?: string; + 'firstName'?: string; + 'lastName'?: string; + 'email'?: string; + 'password'?: string; + 'phone'?: string; /** * User Status */ - 'userStatus': number; + 'userStatus'?: number; static discriminator = undefined; @@ -428,8 +428,9 @@ export interface Authentication { } export class HttpBasicAuth implements Authentication { - public username: string; - public password: string; + public username: string = ''; + public password: string = ''; + applyToRequest(requestOptions: localVarRequest.Options): void { requestOptions.auth = { username: this.username, password: this.password @@ -438,7 +439,7 @@ export class HttpBasicAuth implements Authentication { } export class ApiKeyAuth implements Authentication { - public apiKey: string; + public apiKey: string = ''; constructor(private location: string, private paramName: string) { } @@ -453,7 +454,7 @@ export class ApiKeyAuth implements Authentication { } export class OAuth implements Authentication { - public accessToken: string; + public accessToken: string = ''; applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { @@ -463,8 +464,9 @@ export class OAuth implements Authentication { } export class VoidAuth implements Authentication { - public username: string; - public password: string; + public username: string = ''; + public password: string = ''; + applyToRequest(_: localVarRequest.Options): void { // Do nothing } @@ -1507,7 +1509,7 @@ export class UserApi { /** * * @summary Get user by user name - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { const localVarPath = this.basePath + '/user/{username}' diff --git a/samples/client/petstore/typescript-node/npm/.swagger-codegen-ignore b/samples/client/petstore/typescript-node/npm/.swagger-codegen-ignore index e69de29bb2d1..f521f8128243 100644 --- a/samples/client/petstore/typescript-node/npm/.swagger-codegen-ignore +++ b/samples/client/petstore/typescript-node/npm/.swagger-codegen-ignore @@ -0,0 +1,4 @@ +# Do not overwrite package.json file when re-generating typescript-node client +# as the package file as been modified to include dependencies required for +# testing the generated client. +package.json diff --git a/samples/client/petstore/typescript-node/npm/.swagger-codegen/VERSION b/samples/client/petstore/typescript-node/npm/.swagger-codegen/VERSION index a6254504e401..855ff9501eb8 100644 --- a/samples/client/petstore/typescript-node/npm/.swagger-codegen/VERSION +++ b/samples/client/petstore/typescript-node/npm/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.1 \ No newline at end of file +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/npm/api.d.ts b/samples/client/petstore/typescript-node/npm/api.d.ts index 8b1e4d31baca..535a6c528d77 100644 --- a/samples/client/petstore/typescript-node/npm/api.d.ts +++ b/samples/client/petstore/typescript-node/npm/api.d.ts @@ -5,9 +5,9 @@ import localVarRequest = require('request'); import http = require('http'); import Promise = require('bluebird'); export declare class ApiResponse { - 'code': number; - 'type': string; - 'message': string; + 'code'?: number; + 'type'?: string; + 'message'?: string; static discriminator: undefined; static attributeTypeMap: Array<{ name: string; @@ -21,8 +21,8 @@ export declare class ApiResponse { }[]; } export declare class Category { - 'id': number; - 'name': string; + 'id'?: number; + 'name'?: string; static discriminator: undefined; static attributeTypeMap: Array<{ name: string; @@ -36,12 +36,12 @@ export declare class Category { }[]; } export declare class Order { - 'id': number; - 'petId': number; - 'quantity': number; - 'shipDate': Date; - 'status': Order.StatusEnum; - 'complete': boolean; + 'id'?: number; + 'petId'?: number; + 'quantity'?: number; + 'shipDate'?: Date; + 'status'?: Order.StatusEnum; + 'complete'?: boolean; static discriminator: undefined; static attributeTypeMap: Array<{ name: string; @@ -62,12 +62,12 @@ export declare namespace Order { } } export declare class Pet { - 'id': number; - 'category': Category; + 'id'?: number; + 'category'?: Category; 'name': string; 'photoUrls': Array; - 'tags': Array; - 'status': Pet.StatusEnum; + 'tags'?: Array; + 'status'?: Pet.StatusEnum; static discriminator: undefined; static attributeTypeMap: Array<{ name: string; @@ -88,8 +88,8 @@ export declare namespace Pet { } } export declare class Tag { - 'id': number; - 'name': string; + 'id'?: number; + 'name'?: string; static discriminator: undefined; static attributeTypeMap: Array<{ name: string; @@ -103,14 +103,14 @@ export declare class Tag { }[]; } export declare class User { - 'id': number; - 'username': string; - 'firstName': string; - 'lastName': string; - 'email': string; - 'password': string; - 'phone': string; - 'userStatus': number; + 'id'?: number; + 'username'?: string; + 'firstName'?: string; + 'lastName'?: string; + 'email'?: string; + 'password'?: string; + 'phone'?: string; + 'userStatus'?: number; static discriminator: undefined; static attributeTypeMap: Array<{ name: string; @@ -173,7 +173,7 @@ export declare class PetApi { response: http.ClientResponse; body?: any; }>; - findPetsByStatus(status: Array): Promise<{ + findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>): Promise<{ response: http.ClientResponse; body: Array; }>; diff --git a/samples/client/petstore/typescript-node/npm/api.js b/samples/client/petstore/typescript-node/npm/api.js index 2930d77ef2a5..5f1c58df2d77 100644 --- a/samples/client/petstore/typescript-node/npm/api.js +++ b/samples/client/petstore/typescript-node/npm/api.js @@ -361,6 +361,8 @@ var typeMap = { }; var HttpBasicAuth = (function () { function HttpBasicAuth() { + this.username = ''; + this.password = ''; } HttpBasicAuth.prototype.applyToRequest = function (requestOptions) { requestOptions.auth = { @@ -374,6 +376,7 @@ var ApiKeyAuth = (function () { function ApiKeyAuth(location, paramName) { this.location = location; this.paramName = paramName; + this.apiKey = ''; } ApiKeyAuth.prototype.applyToRequest = function (requestOptions) { if (this.location == "query") { @@ -388,6 +391,7 @@ var ApiKeyAuth = (function () { exports.ApiKeyAuth = ApiKeyAuth; var OAuth = (function () { function OAuth() { + this.accessToken = ''; } OAuth.prototype.applyToRequest = function (requestOptions) { if (requestOptions && requestOptions.headers) { @@ -399,6 +403,8 @@ var OAuth = (function () { exports.OAuth = OAuth; var VoidAuth = (function () { function VoidAuth() { + this.username = ''; + this.password = ''; } VoidAuth.prototype.applyToRequest = function (_) { }; @@ -558,7 +564,7 @@ var PetApi = (function () { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } if (status !== undefined) { - localVarQueryParameters['status'] = ObjectSerializer.serialize(status, "Array"); + localVarQueryParameters['status'] = ObjectSerializer.serialize(status, "Array<'available' | 'pending' | 'sold'>"); } var localVarUseFormData = false; var localVarRequestOptions = { diff --git a/samples/client/petstore/typescript-node/npm/api.js.map b/samples/client/petstore/typescript-node/npm/api.js.map index bb019bf15f64..e4aa276234aa 100644 --- a/samples/client/petstore/typescript-node/npm/api.js.map +++ b/samples/client/petstore/typescript-node/npm/api.js.map @@ -1 +1 @@ -{"version":3,"file":"api.js","sourceRoot":"","sources":["api.ts"],"names":[],"mappings":";;AAYA,yCAA4C;AAE5C,kCAAqC;AAErC,IAAI,eAAe,GAAG,+BAA+B,CAAC;AAOtD,IAAI,UAAU,GAAG;IACG,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,SAAS;IACT,MAAM;IACN,OAAO;IACP,QAAQ;IACR,KAAK;CACP,CAAC;AAEnB;IAAA;IAsGA,CAAC;IApGiB,gCAAe,GAA7B,UAA8B,IAAS,EAAE,YAAoB;QACzD,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACpB,MAAM,CAAC,YAAY,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YAC/D,MAAM,CAAC,YAAY,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,YAAY,KAAK,MAAM,CAAC,CAAC,CAAC;YACjC,MAAM,CAAC,YAAY,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;gBACzB,MAAM,CAAC,YAAY,CAAC;YACxB,CAAC;YAED,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;gBACzB,MAAM,CAAC,YAAY,CAAC;YACxB,CAAC;YAGD,IAAI,qBAAqB,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC,aAAa,CAAC;YAChE,EAAE,CAAC,CAAC,qBAAqB,IAAI,IAAI,CAAC,CAAC,CAAC;gBAChC,MAAM,CAAC,YAAY,CAAC;YACxB,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,EAAE,CAAC,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC;oBAC9B,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;gBACvC,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,MAAM,CAAC,YAAY,CAAC;gBACxB,CAAC;YACL,CAAC;QACL,CAAC;IACL,CAAC;IAEa,0BAAS,GAAvB,UAAwB,IAAS,EAAE,IAAY;QAC3C,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACpB,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YACvD,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAC7C,IAAI,OAAO,GAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YACjD,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACnD,IAAI,eAAe,GAAU,EAAE,CAAC;YAChC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC;gBACrB,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;gBACvB,eAAe,CAAC,IAAI,CAAC,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;YACpE,CAAC;YACD,MAAM,CAAC,eAAe,CAAC;QAC3B,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC;YACzB,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC3B,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YACD,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YAGD,IAAI,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,mBAAmB,EAAE,CAAC;YACzD,IAAI,QAAQ,GAA2B,EAAE,CAAC;YAC1C,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,cAAc,CAAC,CAAC,CAAC;gBAC/B,IAAI,aAAa,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;gBAC1C,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;YAChH,CAAC;YACD,MAAM,CAAC,QAAQ,CAAC;QACpB,CAAC;IACL,CAAC;IAEa,4BAAW,GAAzB,UAA0B,IAAS,EAAE,IAAY;QAE7C,IAAI,GAAG,gBAAgB,CAAC,eAAe,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACpD,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACpB,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YACvD,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAC7C,IAAI,OAAO,GAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YACjD,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACnD,IAAI,eAAe,GAAU,EAAE,CAAC;YAChC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC;gBACrB,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;gBACvB,eAAe,CAAC,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;YACtE,CAAC;YACD,MAAM,CAAC,eAAe,CAAC;QAC3B,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC;YACzB,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;QAC1B,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YAED,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YACD,IAAI,QAAQ,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;YACnC,IAAI,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,mBAAmB,EAAE,CAAC;YACzD,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,cAAc,CAAC,CAAC,CAAC;gBAC/B,IAAI,aAAa,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;gBAC1C,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;YAClH,CAAC;YACD,MAAM,CAAC,QAAQ,CAAC;QACpB,CAAC;IACL,CAAC;IACL,uBAAC;AAAD,CAAC,AAtGD,IAsGC;AAKD;IAAA;IA2BA,CAAC;IAHU,+BAAmB,GAA1B;QACI,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC;IACxC,CAAC;IArBM,yBAAa,GAAG,SAAS,CAAC;IAE1B,4BAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,SAAS;YACjB,UAAU,EAAE,SAAS;YACrB,MAAM,EAAE,QAAQ;SACnB;KAAK,CAAC;IAKf,kBAAC;CAAA,AA3BD,IA2BC;AA3BY,kCAAW;AAgCxB;IAAA;IAqBA,CAAC;IAHU,4BAAmB,GAA1B;QACI,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAC;IACrC,CAAC;IAhBM,sBAAa,GAAG,SAAS,CAAC;IAE1B,yBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;KAAK,CAAC;IAKf,eAAC;CAAA,AArBD,IAqBC;AArBY,4BAAQ;AA0BrB;IAAA;IAgDA,CAAC;IAHU,yBAAmB,GAA1B;QACI,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC;IAClC,CAAC;IApCM,mBAAa,GAAG,SAAS,CAAC;IAE1B,sBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,MAAM;SACjB;QACD;YACI,MAAM,EAAE,QAAQ;YAChB,UAAU,EAAE,QAAQ;YACpB,MAAM,EAAE,kBAAkB;SAC7B;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,SAAS;SACpB;KAAK,CAAC;IAKf,YAAC;CAAA,AAhDD,IAgDC;AAhDY,sBAAK;AAkDlB,WAAiB,KAAK;IAClB,IAAY,UAIX;IAJD,WAAY,UAAU;QAClB,kCAAe,QAAQ,YAAA,CAAA;QACvB,oCAAiB,UAAU,cAAA,CAAA;QAC3B,qCAAkB,WAAW,eAAA,CAAA;IACjC,CAAC,EAJW,UAAU,GAAV,gBAAU,KAAV,gBAAU,QAIrB;AACL,CAAC,EANgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAMrB;AAxDY,sBAAK;AA4DlB;IAAA;IAgDA,CAAC;IAHU,uBAAmB,GAA1B;QACI,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAChC,CAAC;IApCM,iBAAa,GAAG,SAAS,CAAC;IAE1B,oBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,UAAU;SACrB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,WAAW;YACnB,UAAU,EAAE,WAAW;YACvB,MAAM,EAAE,eAAe;SAC1B;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,YAAY;SACvB;QACD;YACI,MAAM,EAAE,QAAQ;YAChB,UAAU,EAAE,QAAQ;YACpB,MAAM,EAAE,gBAAgB;SAC3B;KAAK,CAAC;IAKf,UAAC;CAAA,AAhDD,IAgDC;AAhDY,kBAAG;AAkDhB,WAAiB,GAAG;IAChB,IAAY,UAIX;IAJD,WAAY,UAAU;QAClB,qCAAkB,WAAW,eAAA,CAAA;QAC7B,mCAAgB,SAAS,aAAA,CAAA;QACzB,gCAAa,MAAM,UAAA,CAAA;IACvB,CAAC,EAJW,UAAU,GAAV,cAAU,KAAV,cAAU,QAIrB;AACL,CAAC,EANgB,GAAG,GAAH,WAAG,KAAH,WAAG,QAMnB;AAxDY,kBAAG;AA4DhB;IAAA;IAqBA,CAAC;IAHU,uBAAmB,GAA1B;QACI,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAChC,CAAC;IAhBM,iBAAa,GAAG,SAAS,CAAC;IAE1B,oBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;KAAK,CAAC;IAKf,UAAC;CAAA,AArBD,IAqBC;AArBY,kBAAG;AA0BhB;IAAA;IA4DA,CAAC;IAHU,wBAAmB,GAA1B;QACI,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC;IACjC,CAAC;IA9CM,kBAAa,GAAG,SAAS,CAAC;IAE1B,qBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,WAAW;YACnB,UAAU,EAAE,WAAW;YACvB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,YAAY;YACpB,UAAU,EAAE,YAAY;YACxB,MAAM,EAAE,QAAQ;SACnB;KAAK,CAAC;IAKf,WAAC;CAAA,AA5DD,IA4DC;AA5DY,oBAAI;AA+DjB,IAAI,QAAQ,GAA2B;IAC/B,kBAAkB,EAAE,KAAK,CAAC,UAAU;IACpC,gBAAgB,EAAE,GAAG,CAAC,UAAU;CACvC,CAAA;AAED,IAAI,OAAO,GAA2B;IAClC,aAAa,EAAE,WAAW;IAC1B,UAAU,EAAE,QAAQ;IACpB,OAAO,EAAE,KAAK;IACd,KAAK,EAAE,GAAG;IACV,KAAK,EAAE,GAAG;IACV,MAAM,EAAE,IAAI;CACf,CAAA;AASD;IAAA;IAQA,CAAC;IALG,sCAAc,GAAd,UAAe,cAAuC;QAClD,cAAc,CAAC,IAAI,GAAG;YAClB,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACnD,CAAA;IACL,CAAC;IACL,oBAAC;AAAD,CAAC,AARD,IAQC;AARY,sCAAa;AAU1B;IAGI,oBAAoB,QAAgB,EAAU,SAAiB;QAA3C,aAAQ,GAAR,QAAQ,CAAQ;QAAU,cAAS,GAAT,SAAS,CAAQ;IAC/D,CAAC;IAED,mCAAc,GAAd,UAAe,cAAuC;QAClD,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,OAAO,CAAC,CAAC,CAAC;YACrB,cAAc,CAAC,EAAG,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3D,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,QAAQ,IAAI,cAAc,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;YAC/E,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;QACzD,CAAC;IACL,CAAC;IACL,iBAAC;AAAD,CAAC,AAbD,IAaC;AAbY,gCAAU;AAevB;IAAA;IAQA,CAAC;IALG,8BAAc,GAAd,UAAe,cAAuC;QAClD,EAAE,CAAC,CAAC,cAAc,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;YAC3C,cAAc,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC;QAC3E,CAAC;IACL,CAAC;IACL,YAAC;AAAD,CAAC,AARD,IAQC;AARY,sBAAK;AAUlB;IAAA;IAMA,CAAC;IAHG,iCAAc,GAAd,UAAe,CAA0B;IAEzC,CAAC;IACL,eAAC;AAAD,CAAC,AAND,IAMC;AANY,4BAAQ;AAQrB,IAAY,aAEX;AAFD,WAAY,aAAa;IACrB,uDAAO,CAAA;AACX,CAAC,EAFW,aAAa,GAAb,qBAAa,KAAb,qBAAa,QAExB;AAED;IAYI,gBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,cAAS,GAAG,eAAe,CAAC;QAC5B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,kCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAED,sBAAI,4BAAQ;aAIZ;YACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;aAND,UAAa,QAAgB;YACzB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC9B,CAAC;;;OAAA;IAMM,yCAAwB,GAA/B,UAAgC,IAAoB;QACvD,IAAI,CAAC,eAAe,CAAC,OAAO,GAAG,IAAI,CAAC;IACjC,CAAC;IAEM,0BAAS,GAAhB,UAAiB,GAAkB,EAAE,KAAa;QAC7C,IAAI,CAAC,eAAuB,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IACrE,CAAC;IAED,sBAAI,+BAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IAMM,uBAAM,GAAb,UAAe,IAAS;QACpB,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC;QAC5C,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,oEAAoE,CAAC,CAAC;QAC1F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC;SAChD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,0BAAS,GAAhB,UAAkB,KAAa,EAAE,MAAe;QAC5C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAED,oBAAoB,CAAC,SAAS,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAE/E,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,iCAAgB,GAAvB,UAAyB,MAAqB;QAC1C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,mBAAmB,CAAC;QACzD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,MAAM,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,gFAAgF,CAAC,CAAC;QACtG,CAAC;QAED,EAAE,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC;YACvB,uBAAuB,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;QAC5F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwD,UAAC,OAAO,EAAE,MAAM;YACtF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;oBACxD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAc,GAArB,UAAuB,IAAmB;QACtC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,iBAAiB,CAAC;QACvD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAED,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,uBAAuB,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;QACxF,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwD,UAAC,OAAO,EAAE,MAAM;YACtF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;oBACxD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,2BAAU,GAAjB,UAAmB,KAAa;QAC5B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;QAC/F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAiD,UAAC,OAAO,EAAE,MAAM;YAC/E,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;oBACjD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,0BAAS,GAAhB,UAAkB,IAAS;QACvB,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC;QAC5C,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;QAC7F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC;SAChD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAQM,kCAAiB,GAAxB,UAA0B,KAAa,EAAE,IAAa,EAAE,MAAe;QACnE,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,gFAAgF,CAAC,CAAC;QACtG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,kBAAkB,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC5E,CAAC;QAED,EAAE,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC;YACvB,kBAAkB,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAChF,CAAC;QAED,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAQM,2BAAU,GAAjB,UAAmB,KAAa,EAAE,kBAA2B,EAAE,IAAa;QACxE,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,0BAA0B;aAC1D,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;QAC/F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,EAAE,CAAC,CAAC,kBAAkB,KAAK,SAAS,CAAC,CAAC,CAAC;YACnC,kBAAkB,CAAC,oBAAoB,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,kBAAkB,EAAE,QAAQ,CAAC,CAAC;QACxG,CAAC;QAED,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,kBAAkB,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;QACtC,CAAC;QACD,mBAAmB,GAAG,IAAI,CAAC;QAE3B,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAyD,UAAC,OAAO,EAAE,MAAM;YACvF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;oBACzD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,aAAC;AAAD,CAAC,AAhgBD,IAggBC;AAhgBY,wBAAM;AAigBnB,IAAY,eAEX;AAFD,WAAY,eAAe;IACvB,2DAAO,CAAA;AACX,CAAC,EAFW,eAAe,GAAf,uBAAe,KAAf,uBAAe,QAE1B;AAED;IAYI,kBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,cAAS,GAAG,eAAe,CAAC;QAC5B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,oCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAED,sBAAI,8BAAQ;aAIZ;YACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;aAND,UAAa,QAAgB;YACzB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC9B,CAAC;;;OAAA;IAMM,2CAAwB,GAA/B,UAAgC,IAAoB;QACvD,IAAI,CAAC,eAAe,CAAC,OAAO,GAAG,IAAI,CAAC;IACjC,CAAC;IAEM,4BAAS,GAAhB,UAAiB,GAAoB,EAAE,KAAa;QAC/C,IAAI,CAAC,eAAuB,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IACvE,CAAC;IAED,sBAAI,iCAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IAMM,8BAAW,GAAlB,UAAoB,OAAe;QAC/B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,wBAAwB;aACxD,OAAO,CAAC,GAAG,GAAG,SAAS,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;QACzE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC;YAC5C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAKM,+BAAY,GAAnB;QACI,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAC;QACxD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwE,UAAC,OAAO,EAAE,MAAM;YACtG,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,4BAA4B,CAAC,CAAC;oBACxE,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAY,GAAnB,UAAqB,OAAe;QAChC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,wBAAwB;aACxD,OAAO,CAAC,GAAG,GAAG,SAAS,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;QACzE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC;YAC5C,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC;QACnG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAmD,UAAC,OAAO,EAAE,MAAM;YACjF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;oBACnD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,6BAAU,GAAjB,UAAmB,IAAW;QAC1B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;QACpD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC;SAClD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAmD,UAAC,OAAO,EAAE,MAAM;YACjF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;oBACnD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,eAAC;AAAD,CAAC,AA7PD,IA6PC;AA7PY,4BAAQ;AA8PrB,IAAY,cAEX;AAFD,WAAY,cAAc;IACtB,yDAAO,CAAA;AACX,CAAC,EAFW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAEzB;AAED;IAYI,iBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,cAAS,GAAG,eAAe,CAAC;QAC5B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,mCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAED,sBAAI,6BAAQ;aAIZ;YACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;aAND,UAAa,QAAgB;YACzB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC9B,CAAC;;;OAAA;IAMM,0CAAwB,GAA/B,UAAgC,IAAoB;QACvD,IAAI,CAAC,eAAe,CAAC,OAAO,GAAG,IAAI,CAAC;IACjC,CAAC;IAEM,2BAAS,GAAhB,UAAiB,GAAmB,EAAE,KAAa;QAC9C,IAAI,CAAC,eAAuB,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IACtE,CAAC;IAED,sBAAI,gCAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IAMM,4BAAU,GAAjB,UAAmB,IAAU;QACzB,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QAC7C,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;SACjD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,2CAAyB,GAAhC,UAAkC,IAAiB;QAC/C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,uBAAuB,CAAC;QAC7D,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,uFAAuF,CAAC,CAAC;QAC7G,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,aAAa,CAAC;SACxD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,0CAAwB,GAA/B,UAAiC,IAAiB;QAC9C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,sBAAsB,CAAC;QAC5D,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,sFAAsF,CAAC,CAAC;QAC5G,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,aAAa,CAAC;SACxD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,4BAAU,GAAjB,UAAmB,QAAgB;QAC/B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC3E,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAa,GAApB,UAAsB,QAAgB;QAClC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC3E,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,+EAA+E,CAAC,CAAC;QACrG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;oBAClD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,2BAAS,GAAhB,UAAkB,QAAgB,EAAE,QAAgB;QAChD,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC;QACnD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,2EAA2E,CAAC,CAAC;QACjG,CAAC;QAGD,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,2EAA2E,CAAC,CAAC;QACjG,CAAC;QAED,EAAE,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YACzB,uBAAuB,CAAC,UAAU,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QACzF,CAAC;QAED,EAAE,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YACzB,uBAAuB,CAAC,UAAU,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QACzF,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAoD,UAAC,OAAO,EAAE,MAAM;YAClF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;oBACpD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAKM,4BAAU,GAAjB;QACI,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;QACpD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,4BAAU,GAAjB,UAAmB,QAAgB,EAAE,IAAU;QAC3C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC3E,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAGD,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;SACjD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,cAAC;AAAD,CAAC,AA9dD,IA8dC;AA9dY,0BAAO"} \ No newline at end of file +{"version":3,"file":"api.js","sourceRoot":"","sources":["api.ts"],"names":[],"mappings":";;AAYA,yCAA4C;AAE5C,kCAAqC;AAErC,IAAI,eAAe,GAAG,+BAA+B,CAAC;AAOtD,IAAI,UAAU,GAAG;IACG,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,SAAS;IACT,MAAM;IACN,OAAO;IACP,QAAQ;IACR,KAAK;CACP,CAAC;AAEnB;IAAA;IAsGA,CAAC;IApGiB,gCAAe,GAA7B,UAA8B,IAAS,EAAE,YAAoB;QACzD,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACpB,MAAM,CAAC,YAAY,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YAC/D,MAAM,CAAC,YAAY,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,YAAY,KAAK,MAAM,CAAC,CAAC,CAAC;YACjC,MAAM,CAAC,YAAY,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;gBACzB,MAAM,CAAC,YAAY,CAAC;YACxB,CAAC;YAED,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;gBACzB,MAAM,CAAC,YAAY,CAAC;YACxB,CAAC;YAGD,IAAI,qBAAqB,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC,aAAa,CAAC;YAChE,EAAE,CAAC,CAAC,qBAAqB,IAAI,IAAI,CAAC,CAAC,CAAC;gBAChC,MAAM,CAAC,YAAY,CAAC;YACxB,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,EAAE,CAAC,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC;oBAC9B,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;gBACvC,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,MAAM,CAAC,YAAY,CAAC;gBACxB,CAAC;YACL,CAAC;QACL,CAAC;IACL,CAAC;IAEa,0BAAS,GAAvB,UAAwB,IAAS,EAAE,IAAY;QAC3C,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACpB,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YACvD,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAC7C,IAAI,OAAO,GAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YACjD,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACnD,IAAI,eAAe,GAAU,EAAE,CAAC;YAChC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC;gBACrB,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;gBACvB,eAAe,CAAC,IAAI,CAAC,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;YACpE,CAAC;YACD,MAAM,CAAC,eAAe,CAAC;QAC3B,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC;YACzB,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC3B,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YACD,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YAGD,IAAI,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,mBAAmB,EAAE,CAAC;YACzD,IAAI,QAAQ,GAA2B,EAAE,CAAC;YAC1C,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,cAAc,CAAC,CAAC,CAAC;gBAC/B,IAAI,aAAa,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;gBAC1C,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;YAChH,CAAC;YACD,MAAM,CAAC,QAAQ,CAAC;QACpB,CAAC;IACL,CAAC;IAEa,4BAAW,GAAzB,UAA0B,IAAS,EAAE,IAAY;QAE7C,IAAI,GAAG,gBAAgB,CAAC,eAAe,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACpD,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACpB,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YACvD,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAC7C,IAAI,OAAO,GAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YACjD,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACnD,IAAI,eAAe,GAAU,EAAE,CAAC;YAChC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC;gBACrB,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;gBACvB,eAAe,CAAC,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;YACtE,CAAC;YACD,MAAM,CAAC,eAAe,CAAC;QAC3B,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC;YACzB,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;QAC1B,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YAED,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YACD,IAAI,QAAQ,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;YACnC,IAAI,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,mBAAmB,EAAE,CAAC;YACzD,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,cAAc,CAAC,CAAC,CAAC;gBAC/B,IAAI,aAAa,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;gBAC1C,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;YAClH,CAAC;YACD,MAAM,CAAC,QAAQ,CAAC;QACpB,CAAC;IACL,CAAC;IACL,uBAAC;AAAD,CAAC,AAtGD,IAsGC;AAKD;IAAA;IA2BA,CAAC;IAHU,+BAAmB,GAA1B;QACI,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC;IACxC,CAAC;IArBM,yBAAa,GAAG,SAAS,CAAC;IAE1B,4BAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,SAAS;YACjB,UAAU,EAAE,SAAS;YACrB,MAAM,EAAE,QAAQ;SACnB;KAAK,CAAC;IAKf,kBAAC;CAAA,AA3BD,IA2BC;AA3BY,kCAAW;AAgCxB;IAAA;IAqBA,CAAC;IAHU,4BAAmB,GAA1B;QACI,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAC;IACrC,CAAC;IAhBM,sBAAa,GAAG,SAAS,CAAC;IAE1B,yBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;KAAK,CAAC;IAKf,eAAC;CAAA,AArBD,IAqBC;AArBY,4BAAQ;AA0BrB;IAAA;IAgDA,CAAC;IAHU,yBAAmB,GAA1B;QACI,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC;IAClC,CAAC;IApCM,mBAAa,GAAG,SAAS,CAAC;IAE1B,sBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,MAAM;SACjB;QACD;YACI,MAAM,EAAE,QAAQ;YAChB,UAAU,EAAE,QAAQ;YACpB,MAAM,EAAE,kBAAkB;SAC7B;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,SAAS;SACpB;KAAK,CAAC;IAKf,YAAC;CAAA,AAhDD,IAgDC;AAhDY,sBAAK;AAkDlB,WAAiB,KAAK;IAClB,IAAY,UAIX;IAJD,WAAY,UAAU;QAClB,kCAAe,QAAQ,YAAA,CAAA;QACvB,oCAAiB,UAAU,cAAA,CAAA;QAC3B,qCAAkB,WAAW,eAAA,CAAA;IACjC,CAAC,EAJW,UAAU,GAAV,gBAAU,KAAV,gBAAU,QAIrB;AACL,CAAC,EANgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAMrB;AAxDY,sBAAK;AA4DlB;IAAA;IAgDA,CAAC;IAHU,uBAAmB,GAA1B;QACI,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAChC,CAAC;IApCM,iBAAa,GAAG,SAAS,CAAC;IAE1B,oBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,UAAU;SACrB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,WAAW;YACnB,UAAU,EAAE,WAAW;YACvB,MAAM,EAAE,eAAe;SAC1B;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,YAAY;SACvB;QACD;YACI,MAAM,EAAE,QAAQ;YAChB,UAAU,EAAE,QAAQ;YACpB,MAAM,EAAE,gBAAgB;SAC3B;KAAK,CAAC;IAKf,UAAC;CAAA,AAhDD,IAgDC;AAhDY,kBAAG;AAkDhB,WAAiB,GAAG;IAChB,IAAY,UAIX;IAJD,WAAY,UAAU;QAClB,qCAAkB,WAAW,eAAA,CAAA;QAC7B,mCAAgB,SAAS,aAAA,CAAA;QACzB,gCAAa,MAAM,UAAA,CAAA;IACvB,CAAC,EAJW,UAAU,GAAV,cAAU,KAAV,cAAU,QAIrB;AACL,CAAC,EANgB,GAAG,GAAH,WAAG,KAAH,WAAG,QAMnB;AAxDY,kBAAG;AA4DhB;IAAA;IAqBA,CAAC;IAHU,uBAAmB,GAA1B;QACI,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAChC,CAAC;IAhBM,iBAAa,GAAG,SAAS,CAAC;IAE1B,oBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;KAAK,CAAC;IAKf,UAAC;CAAA,AArBD,IAqBC;AArBY,kBAAG;AA0BhB;IAAA;IA4DA,CAAC;IAHU,wBAAmB,GAA1B;QACI,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC;IACjC,CAAC;IA9CM,kBAAa,GAAG,SAAS,CAAC;IAE1B,qBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,WAAW;YACnB,UAAU,EAAE,WAAW;YACvB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,YAAY;YACpB,UAAU,EAAE,YAAY;YACxB,MAAM,EAAE,QAAQ;SACnB;KAAK,CAAC;IAKf,WAAC;CAAA,AA5DD,IA4DC;AA5DY,oBAAI;AA+DjB,IAAI,QAAQ,GAA2B;IAC/B,kBAAkB,EAAE,KAAK,CAAC,UAAU;IACpC,gBAAgB,EAAE,GAAG,CAAC,UAAU;CACvC,CAAA;AAED,IAAI,OAAO,GAA2B;IAClC,aAAa,EAAE,WAAW;IAC1B,UAAU,EAAE,QAAQ;IACpB,OAAO,EAAE,KAAK;IACd,KAAK,EAAE,GAAG;IACV,KAAK,EAAE,GAAG;IACV,MAAM,EAAE,IAAI;CACf,CAAA;AASD;IAAA;QACW,aAAQ,GAAW,EAAE,CAAC;QACtB,aAAQ,GAAW,EAAE,CAAC;IAOjC,CAAC;IALG,sCAAc,GAAd,UAAe,cAAuC;QAClD,cAAc,CAAC,IAAI,GAAG;YAClB,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACnD,CAAA;IACL,CAAC;IACL,oBAAC;AAAD,CAAC,AATD,IASC;AATY,sCAAa;AAW1B;IAGI,oBAAoB,QAAgB,EAAU,SAAiB;QAA3C,aAAQ,GAAR,QAAQ,CAAQ;QAAU,cAAS,GAAT,SAAS,CAAQ;QAFxD,WAAM,GAAW,EAAE,CAAC;IAG3B,CAAC;IAED,mCAAc,GAAd,UAAe,cAAuC;QAClD,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,OAAO,CAAC,CAAC,CAAC;YACrB,cAAc,CAAC,EAAG,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3D,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,QAAQ,IAAI,cAAc,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;YAC/E,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;QACzD,CAAC;IACL,CAAC;IACL,iBAAC;AAAD,CAAC,AAbD,IAaC;AAbY,gCAAU;AAevB;IAAA;QACW,gBAAW,GAAW,EAAE,CAAC;IAOpC,CAAC;IALG,8BAAc,GAAd,UAAe,cAAuC;QAClD,EAAE,CAAC,CAAC,cAAc,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;YAC3C,cAAc,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC;QAC3E,CAAC;IACL,CAAC;IACL,YAAC;AAAD,CAAC,AARD,IAQC;AARY,sBAAK;AAUlB;IAAA;QACW,aAAQ,GAAW,EAAE,CAAC;QACtB,aAAQ,GAAW,EAAE,CAAC;IAKjC,CAAC;IAHG,iCAAc,GAAd,UAAe,CAA0B;IAEzC,CAAC;IACL,eAAC;AAAD,CAAC,AAPD,IAOC;AAPY,4BAAQ;AASrB,IAAY,aAEX;AAFD,WAAY,aAAa;IACrB,uDAAO,CAAA;AACX,CAAC,EAFW,aAAa,GAAb,qBAAa,KAAb,qBAAa,QAExB;AAED;IAYI,gBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,cAAS,GAAG,eAAe,CAAC;QAC5B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,kCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAED,sBAAI,4BAAQ;aAIZ;YACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;aAND,UAAa,QAAgB;YACzB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC9B,CAAC;;;OAAA;IAMM,yCAAwB,GAA/B,UAAgC,IAAoB;QACvD,IAAI,CAAC,eAAe,CAAC,OAAO,GAAG,IAAI,CAAC;IACjC,CAAC;IAEM,0BAAS,GAAhB,UAAiB,GAAkB,EAAE,KAAa;QAC7C,IAAI,CAAC,eAAuB,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IACrE,CAAC;IAED,sBAAI,+BAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IAMM,uBAAM,GAAb,UAAe,IAAS;QACpB,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC;QAC5C,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,oEAAoE,CAAC,CAAC;QAC1F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC;SAChD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,0BAAS,GAAhB,UAAkB,KAAa,EAAE,MAAe;QAC5C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAED,oBAAoB,CAAC,SAAS,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAE/E,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,iCAAgB,GAAvB,UAAyB,MAA+C;QACpE,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,mBAAmB,CAAC;QACzD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,MAAM,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,gFAAgF,CAAC,CAAC;QACtG,CAAC;QAED,EAAE,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC;YACvB,uBAAuB,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,yCAAyC,CAAC,CAAC;QACtH,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwD,UAAC,OAAO,EAAE,MAAM;YACtF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;oBACxD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAc,GAArB,UAAuB,IAAmB;QACtC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,iBAAiB,CAAC;QACvD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAED,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,uBAAuB,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;QACxF,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwD,UAAC,OAAO,EAAE,MAAM;YACtF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;oBACxD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,2BAAU,GAAjB,UAAmB,KAAa;QAC5B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;QAC/F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAiD,UAAC,OAAO,EAAE,MAAM;YAC/E,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;oBACjD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,0BAAS,GAAhB,UAAkB,IAAS;QACvB,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC;QAC5C,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;QAC7F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC;SAChD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAQM,kCAAiB,GAAxB,UAA0B,KAAa,EAAE,IAAa,EAAE,MAAe;QACnE,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,gFAAgF,CAAC,CAAC;QACtG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,kBAAkB,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC5E,CAAC;QAED,EAAE,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC;YACvB,kBAAkB,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAChF,CAAC;QAED,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAQM,2BAAU,GAAjB,UAAmB,KAAa,EAAE,kBAA2B,EAAE,IAAa;QACxE,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,0BAA0B;aAC1D,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;QAC/F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,EAAE,CAAC,CAAC,kBAAkB,KAAK,SAAS,CAAC,CAAC,CAAC;YACnC,kBAAkB,CAAC,oBAAoB,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,kBAAkB,EAAE,QAAQ,CAAC,CAAC;QACxG,CAAC;QAED,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,kBAAkB,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;QACtC,CAAC;QACD,mBAAmB,GAAG,IAAI,CAAC;QAE3B,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAyD,UAAC,OAAO,EAAE,MAAM;YACvF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;oBACzD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,aAAC;AAAD,CAAC,AAhgBD,IAggBC;AAhgBY,wBAAM;AAigBnB,IAAY,eAEX;AAFD,WAAY,eAAe;IACvB,2DAAO,CAAA;AACX,CAAC,EAFW,eAAe,GAAf,uBAAe,KAAf,uBAAe,QAE1B;AAED;IAYI,kBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,cAAS,GAAG,eAAe,CAAC;QAC5B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,oCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAED,sBAAI,8BAAQ;aAIZ;YACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;aAND,UAAa,QAAgB;YACzB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC9B,CAAC;;;OAAA;IAMM,2CAAwB,GAA/B,UAAgC,IAAoB;QACvD,IAAI,CAAC,eAAe,CAAC,OAAO,GAAG,IAAI,CAAC;IACjC,CAAC;IAEM,4BAAS,GAAhB,UAAiB,GAAoB,EAAE,KAAa;QAC/C,IAAI,CAAC,eAAuB,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IACvE,CAAC;IAED,sBAAI,iCAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IAMM,8BAAW,GAAlB,UAAoB,OAAe;QAC/B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,wBAAwB;aACxD,OAAO,CAAC,GAAG,GAAG,SAAS,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;QACzE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC;YAC5C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAKM,+BAAY,GAAnB;QACI,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAC;QACxD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwE,UAAC,OAAO,EAAE,MAAM;YACtG,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,4BAA4B,CAAC,CAAC;oBACxE,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAY,GAAnB,UAAqB,OAAe;QAChC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,wBAAwB;aACxD,OAAO,CAAC,GAAG,GAAG,SAAS,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;QACzE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC;YAC5C,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC;QACnG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAmD,UAAC,OAAO,EAAE,MAAM;YACjF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;oBACnD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,6BAAU,GAAjB,UAAmB,IAAW;QAC1B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;QACpD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC;SAClD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAmD,UAAC,OAAO,EAAE,MAAM;YACjF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;oBACnD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,eAAC;AAAD,CAAC,AA7PD,IA6PC;AA7PY,4BAAQ;AA8PrB,IAAY,cAEX;AAFD,WAAY,cAAc;IACtB,yDAAO,CAAA;AACX,CAAC,EAFW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAEzB;AAED;IAYI,iBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,cAAS,GAAG,eAAe,CAAC;QAC5B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,mCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAED,sBAAI,6BAAQ;aAIZ;YACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;aAND,UAAa,QAAgB;YACzB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC9B,CAAC;;;OAAA;IAMM,0CAAwB,GAA/B,UAAgC,IAAoB;QACvD,IAAI,CAAC,eAAe,CAAC,OAAO,GAAG,IAAI,CAAC;IACjC,CAAC;IAEM,2BAAS,GAAhB,UAAiB,GAAmB,EAAE,KAAa;QAC9C,IAAI,CAAC,eAAuB,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IACtE,CAAC;IAED,sBAAI,gCAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IAMM,4BAAU,GAAjB,UAAmB,IAAU;QACzB,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QAC7C,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;SACjD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,2CAAyB,GAAhC,UAAkC,IAAiB;QAC/C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,uBAAuB,CAAC;QAC7D,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,uFAAuF,CAAC,CAAC;QAC7G,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,aAAa,CAAC;SACxD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,0CAAwB,GAA/B,UAAiC,IAAiB;QAC9C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,sBAAsB,CAAC;QAC5D,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,sFAAsF,CAAC,CAAC;QAC5G,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,aAAa,CAAC;SACxD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,4BAAU,GAAjB,UAAmB,QAAgB;QAC/B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC3E,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAa,GAApB,UAAsB,QAAgB;QAClC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC3E,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,+EAA+E,CAAC,CAAC;QACrG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;oBAClD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,2BAAS,GAAhB,UAAkB,QAAgB,EAAE,QAAgB;QAChD,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC;QACnD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,2EAA2E,CAAC,CAAC;QACjG,CAAC;QAGD,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,2EAA2E,CAAC,CAAC;QACjG,CAAC;QAED,EAAE,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YACzB,uBAAuB,CAAC,UAAU,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QACzF,CAAC;QAED,EAAE,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YACzB,uBAAuB,CAAC,UAAU,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QACzF,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAoD,UAAC,OAAO,EAAE,MAAM;YAClF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;oBACpD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAKM,4BAAU,GAAjB;QACI,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;QACpD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,4BAAU,GAAjB,UAAmB,QAAgB,EAAE,IAAU;QAC3C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC3E,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAGD,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;SACjD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,cAAC;AAAD,CAAC,AA9dD,IA8dC;AA9dY,0BAAO"} \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/npm/api.ts b/samples/client/petstore/typescript-node/npm/api.ts index 1e75275a0669..2a41b799beaa 100644 --- a/samples/client/petstore/typescript-node/npm/api.ts +++ b/samples/client/petstore/typescript-node/npm/api.ts @@ -140,9 +140,9 @@ class ObjectSerializer { * Describes the result of uploading an image resource */ export class ApiResponse { - 'code': number; - 'type': string; - 'message': string; + 'code'?: number; + 'type'?: string; + 'message'?: string; static discriminator = undefined; @@ -172,8 +172,8 @@ export class ApiResponse { * A category for a pet */ export class Category { - 'id': number; - 'name': string; + 'id'?: number; + 'name'?: string; static discriminator = undefined; @@ -198,15 +198,15 @@ export class Category { * An order for a pets from the pet store */ export class Order { - 'id': number; - 'petId': number; - 'quantity': number; - 'shipDate': Date; + 'id'?: number; + 'petId'?: number; + 'quantity'?: number; + 'shipDate'?: Date; /** * Order Status */ - 'status': Order.StatusEnum; - 'complete': boolean; + 'status'?: Order.StatusEnum; + 'complete'?: boolean; static discriminator = undefined; @@ -258,15 +258,15 @@ export namespace Order { * A pet for sale in the pet store */ export class Pet { - 'id': number; - 'category': Category; + 'id'?: number; + 'category'?: Category; 'name': string; 'photoUrls': Array; - 'tags': Array; + 'tags'?: Array; /** * pet status in the store */ - 'status': Pet.StatusEnum; + 'status'?: Pet.StatusEnum; static discriminator = undefined; @@ -318,8 +318,8 @@ export namespace Pet { * A tag for a pet */ export class Tag { - 'id': number; - 'name': string; + 'id'?: number; + 'name'?: string; static discriminator = undefined; @@ -344,17 +344,17 @@ export class Tag { * A User who is purchasing from the pet store */ export class User { - 'id': number; - 'username': string; - 'firstName': string; - 'lastName': string; - 'email': string; - 'password': string; - 'phone': string; + 'id'?: number; + 'username'?: string; + 'firstName'?: string; + 'lastName'?: string; + 'email'?: string; + 'password'?: string; + 'phone'?: string; /** * User Status */ - 'userStatus': number; + 'userStatus'?: number; static discriminator = undefined; @@ -428,8 +428,9 @@ export interface Authentication { } export class HttpBasicAuth implements Authentication { - public username: string; - public password: string; + public username: string = ''; + public password: string = ''; + applyToRequest(requestOptions: localVarRequest.Options): void { requestOptions.auth = { username: this.username, password: this.password @@ -438,7 +439,7 @@ export class HttpBasicAuth implements Authentication { } export class ApiKeyAuth implements Authentication { - public apiKey: string; + public apiKey: string = ''; constructor(private location: string, private paramName: string) { } @@ -453,7 +454,7 @@ export class ApiKeyAuth implements Authentication { } export class OAuth implements Authentication { - public accessToken: string; + public accessToken: string = ''; applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { @@ -463,8 +464,9 @@ export class OAuth implements Authentication { } export class VoidAuth implements Authentication { - public username: string; - public password: string; + public username: string = ''; + public password: string = ''; + applyToRequest(_: localVarRequest.Options): void { // Do nothing } @@ -1507,7 +1509,7 @@ export class UserApi { /** * * @summary Get user by user name - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { const localVarPath = this.basePath + '/user/{username}' diff --git a/samples/client/petstore/typescript-node/npm/package-lock.json b/samples/client/petstore/typescript-node/npm/package-lock.json index 0d1317de4506..44d62e8f5e3e 100644 --- a/samples/client/petstore/typescript-node/npm/package-lock.json +++ b/samples/client/petstore/typescript-node/npm/package-lock.json @@ -2,6 +2,7 @@ "name": "@swagger/angular2-typescript-petstore", "version": "0.0.1", "lockfileVersion": 1, + "requires": true, "dependencies": { "@types/bluebird": { "version": "3.5.18", @@ -30,11 +31,6 @@ "@types/node": "8.0.51" } }, - "@types/rewire": { - "version": "2.5.28", - "resolved": "https://registry.npmjs.org/@types/rewire/-/rewire-2.5.28.tgz", - "integrity": "sha512-uD0j/AQOa5le7afuK+u+woi8jNKF1vf3DN0H7LCJhft/lNNibUr7VcAesdgtWfEKveZol3ZG1CJqwx2Bhrnl8w==" - }, "ajv": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.3.0.tgz", @@ -46,6 +42,16 @@ "json-schema-traverse": "0.3.1" } }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" + }, "asn1": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", @@ -71,6 +77,158 @@ "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.6.0.tgz", "integrity": "sha1-g+9cqGCysy5KDe7e6MdxudtXRx4=" }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "requires": { + "chalk": "1.1.3", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + } + }, + "babel-core": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-core/-/babel-core-6.26.0.tgz", + "integrity": "sha1-rzL3izGm/O8RnIew/Y2XU/A6C7g=", + "requires": { + "babel-code-frame": "6.26.0", + "babel-generator": "6.26.1", + "babel-helpers": "6.24.1", + "babel-messages": "6.23.0", + "babel-register": "6.26.0", + "babel-runtime": "6.26.0", + "babel-template": "6.26.0", + "babel-traverse": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "convert-source-map": "1.5.1", + "debug": "2.6.9", + "json5": "0.5.1", + "lodash": "4.17.5", + "minimatch": "3.0.4", + "path-is-absolute": "1.0.1", + "private": "0.1.8", + "slash": "1.0.0", + "source-map": "0.5.7" + } + }, + "babel-generator": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", + "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", + "requires": { + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "detect-indent": "4.0.0", + "jsesc": "1.3.0", + "lodash": "4.17.5", + "source-map": "0.5.7", + "trim-right": "1.0.1" + } + }, + "babel-helpers": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helpers/-/babel-helpers-6.24.1.tgz", + "integrity": "sha1-NHHenK7DiOXIUOWX5Yom3fN2ArI=", + "requires": { + "babel-runtime": "6.26.0", + "babel-template": "6.26.0" + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "requires": { + "babel-runtime": "6.26.0" + } + }, + "babel-plugin-transform-es2015-block-scoping": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-block-scoping/-/babel-plugin-transform-es2015-block-scoping-6.26.0.tgz", + "integrity": "sha1-1w9SmcEwjQXBL0Y4E7CgnnOxiV8=", + "requires": { + "babel-runtime": "6.26.0", + "babel-template": "6.26.0", + "babel-traverse": "6.26.0", + "babel-types": "6.26.0", + "lodash": "4.17.5" + } + }, + "babel-register": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-register/-/babel-register-6.26.0.tgz", + "integrity": "sha1-btAhFz4vy0htestFxgCahW9kcHE=", + "requires": { + "babel-core": "6.26.0", + "babel-runtime": "6.26.0", + "core-js": "2.5.3", + "home-or-tmp": "2.0.0", + "lodash": "4.17.5", + "mkdirp": "0.5.1", + "source-map-support": "0.4.18" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "requires": { + "core-js": "2.5.3", + "regenerator-runtime": "0.11.1" + } + }, + "babel-template": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-template/-/babel-template-6.26.0.tgz", + "integrity": "sha1-3gPi0WOWsGn0bdn/+FIfsaDjXgI=", + "requires": { + "babel-runtime": "6.26.0", + "babel-traverse": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "lodash": "4.17.5" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "requires": { + "babel-code-frame": "6.26.0", + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "debug": "2.6.9", + "globals": "9.18.0", + "invariant": "2.2.4", + "lodash": "4.17.5" + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "requires": { + "babel-runtime": "6.26.0", + "esutils": "2.0.2", + "lodash": "4.17.5", + "to-fast-properties": "1.0.3" + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==" + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" + }, "bcrypt-pbkdf": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz", @@ -93,11 +251,32 @@ "hoek": "4.2.0" } }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, "caseless": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, "co": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", @@ -111,6 +290,21 @@ "delayed-stream": "1.0.0" } }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "convert-source-map": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.5.1.tgz", + "integrity": "sha1-uCeAl7m8IpNl3lxiz1/K7YtVmeU=" + }, + "core-js": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", + "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=" + }, "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", @@ -142,11 +336,27 @@ "assert-plus": "1.0.0" } }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, "delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "requires": { + "repeating": "2.0.1" + } + }, "ecc-jsbn": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz", @@ -156,6 +366,16 @@ "jsbn": "0.1.1" } }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=" + }, "extend": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", @@ -199,6 +419,11 @@ "assert-plus": "1.0.0" } }, + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==" + }, "har-schema": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", @@ -213,6 +438,14 @@ "har-schema": "2.0.0" } }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "requires": { + "ansi-regex": "2.1.1" + } + }, "hawk": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/hawk/-/hawk-6.0.2.tgz", @@ -229,6 +462,15 @@ "resolved": "https://registry.npmjs.org/hoek/-/hoek-4.2.0.tgz", "integrity": "sha512-v0XCLxICi9nPfYrS9RL8HbYnXi9obYAeLbSP00BmnZwCK9+Ih9WOjoZ8YoHCoav2csqn4FOz4Orldsy2dmDwmQ==" }, + "home-or-tmp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/home-or-tmp/-/home-or-tmp-2.0.0.tgz", + "integrity": "sha1-42w/LSyufXRqhX440Y1fMqeILbg=", + "requires": { + "os-homedir": "1.0.2", + "os-tmpdir": "1.0.2" + } + }, "http-signature": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", @@ -239,6 +481,22 @@ "sshpk": "1.13.1" } }, + "invariant": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", + "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==", + "requires": { + "loose-envify": "1.3.1" + } + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "requires": { + "number-is-nan": "1.0.1" + } + }, "is-typedarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", @@ -249,12 +507,22 @@ "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" + }, "jsbn": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", "optional": true }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=" + }, "json-schema": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", @@ -270,6 +538,11 @@ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" }, + "json5": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", + "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=" + }, "jsprim": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", @@ -281,6 +554,19 @@ "verror": "1.10.0" } }, + "lodash": { + "version": "4.17.5", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", + "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==" + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "requires": { + "js-tokens": "3.0.2" + } + }, "mime-db": { "version": "1.30.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.30.0.tgz", @@ -294,16 +580,67 @@ "mime-db": "1.30.0" } }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "requires": { + "brace-expansion": "1.1.11" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=" + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "requires": { + "minimist": "0.0.8" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=" + }, "oauth-sign": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.8.2.tgz", "integrity": "sha1-Rqarfwrq2N6unsBWV4C31O/rnUM=" }, + "os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=" + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" + }, "performance-now": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" }, + "private": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/private/-/private-0.1.8.tgz", + "integrity": "sha512-VvivMrbvd2nKkiG38qjULzlc+4Vx4wm/whI9pQD35YrARNnhxeiRktSOhSukRLFNlzg6Br/cJPet5J/u19r/mg==" + }, "punycode": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", @@ -314,6 +651,19 @@ "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", "integrity": "sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A==" }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==" + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "requires": { + "is-finite": "1.0.2" + } + }, "request": { "version": "2.83.0", "resolved": "https://registry.npmjs.org/request/-/request-2.83.0.tgz", @@ -344,15 +694,24 @@ } }, "rewire": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/rewire/-/rewire-2.5.2.tgz", - "integrity": "sha1-ZCfee3/u+n02QBUH62SlOFvFjcc=" + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rewire/-/rewire-3.0.2.tgz", + "integrity": "sha512-ejkkt3qYnsQ38ifc9llAAzuHiGM7kR8N5/mL3aHWgmWwet0OMFcmJB8aTsMV2PBHCWxNVTLCeRfBpEa8X2+1fw==", + "requires": { + "babel-core": "6.26.0", + "babel-plugin-transform-es2015-block-scoping": "6.26.0" + } }, "safe-buffer": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" }, + "slash": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz", + "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=" + }, "sntp": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/sntp/-/sntp-2.1.0.tgz", @@ -361,6 +720,19 @@ "hoek": "4.2.0" } }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "source-map-support": { + "version": "0.4.18", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.4.18.tgz", + "integrity": "sha512-try0/JqxPLF9nOjvSta7tVondkP5dwgyLDjVoyMDlmjugT2lRZ1OfsrYTkCd2hkDnJTKRbO/Rl3orm8vlsUzbA==", + "requires": { + "source-map": "0.5.7" + } + }, "sshpk": { "version": "1.13.1", "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.13.1.tgz", @@ -381,6 +753,24 @@ "resolved": "https://registry.npmjs.org/stringstream/-/stringstream-0.0.5.tgz", "integrity": "sha1-TkhM1N5aC7vuGORjB3EKioFiGHg=" }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "requires": { + "ansi-regex": "2.1.1" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=" + }, "tough-cookie": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.3.3.tgz", @@ -389,6 +779,11 @@ "punycode": "1.4.1" } }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=" + }, "tunnel-agent": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", diff --git a/samples/client/petstore/typescript-node/npm/package.json b/samples/client/petstore/typescript-node/npm/package.json index 907c47f80592..5a45fc9dd45d 100644 --- a/samples/client/petstore/typescript-node/npm/package.json +++ b/samples/client/petstore/typescript-node/npm/package.json @@ -13,15 +13,16 @@ "author": "Swagger Codegen Contributors", "license": "Unlicense", "dependencies": { + "@types/bluebird": "*", + "@types/request": "*", "bluebird": "^3.5.0", "request": "^2.81.0", - "@types/bluebird": "*", - "@types/request": "*" + "rewire": "^3.0.2" }, "devDependencies": { "typescript": "^2.4.2" }, - "publishConfig":{ - "registry":"https://skimdb.npmjs.com/registry" + "publishConfig": { + "registry": "https://skimdb.npmjs.com/registry" } } diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIHelper.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIHelper.swift index b612ff90921a..81e7286d6d40 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIHelper.swift @@ -6,12 +6,11 @@ import Foundation -class APIHelper { - static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { - var destination = [String:Any]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = value +public struct APIHelper { + public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + let destination = source.reduce(into: [String: Any]()) { (result, item) in + if let value = item.value { + result[item.key] = value } } @@ -21,45 +20,46 @@ class APIHelper { return destination } - static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { - var destination = [String:String]() - for (key, nillableValue) in source { - if let value: Any = nillableValue { - destination[key] = "\(value)" + public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + return source.reduce(into: [String: String]()) { (result, item) in + if let collection = item.value as? Array { + result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = "\(value)" } } - return destination } - static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { guard let source = source else { return nil } - var destination = [String:Any]() - let theTrue = NSNumber(value: true as Bool) - let theFalse = NSNumber(value: false as Bool) - for (key, value) in source { - switch value { - case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse: - destination[key] = "\(value as! Bool)" as Any? + + return source.reduce(into: [String: Any](), { (result, item) in + switch item.value { + case let x as Bool: + result[item.key] = x.description default: - destination[key] = value + result[item.key] = item.value } - } - return destination + }) } - static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { - let returnValues = values - .filter { $0.1 != nil } - .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in - URLQueryItem(name: item._key, value:"\(item._value!)") + public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in + if let collection = item.value as? Array { + let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + result.append(URLQueryItem(name: item.key, value: value)) + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: "\(value)")) } - if returnValues.count == 0 { + } + + if destination.isEmpty { return nil } - return returnValues + return destination } - } + diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIs.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIs.swift index 0c654587a391..b00327e6077d 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIs.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIs.swift @@ -16,10 +16,10 @@ open class TestClientAPI { open class RequestBuilder { var credential: URLCredential? var headers: [String:String] - let parameters: [String:Any]? - let isBody: Bool - let method: String - let URLString: String + public let parameters: [String:Any]? + public let isBody: Bool + public let method: String + public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIs/Swift4TestAPI.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIs/Swift4TestAPI.swift index e52fbe8260d5..d7cb7cfe7039 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIs/Swift4TestAPI.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/APIs/Swift4TestAPI.swift @@ -19,7 +19,7 @@ open class Swift4TestAPI { */ open class func getAllModels(clientId: String, completion: @escaping ((_ data: GetAllModelsResult?,_ error: Error?) -> Void)) { getAllModelsWithRequestBuilder(clientId: clientId).execute { (response, error) -> Void in - completion(response?.body, error); + completion(response?.body, error) } } @@ -124,12 +124,11 @@ open class Swift4TestAPI { let path = "/allModels" let URLString = TestClientAPI.basePath + path let parameters: [String:Any]? = nil - - let url = NSURLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + + var url = URLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems([ "client_id": clientId ]) - let requestBuilder: RequestBuilder.Type = TestClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/AlamofireImplementations.swift index 24351523736d..381fddcc81fb 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/AlamofireImplementations.swift @@ -268,7 +268,7 @@ open class AlamofireRequestBuilder: RequestBuilder { fileprivate func getPath(from url : URL) throws -> String { - guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath } diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/JSONEncodingHelper.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/JSONEncodingHelper.swift index 4cf4ac206af5..19ee06b1f487 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/JSONEncodingHelper.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/JSONEncodingHelper.swift @@ -24,4 +24,20 @@ open class JSONEncodingHelper { return params } + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { + var params: Parameters? = nil + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error) + return nil + } + } + + return params + } + } diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/AllPrimitives.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/AllPrimitives.swift index 769b5a7f4750..2ed0ac1df2b0 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/AllPrimitives.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/AllPrimitives.swift @@ -43,6 +43,33 @@ public struct AllPrimitives: Codable { public var myStringEnumArray: [StringEnum]? public var myInlineStringEnum: MyInlineStringEnum? + public init(myInteger: Int?, myIntegerArray: [Int]?, myLong: Int64?, myLongArray: [Int64]?, myFloat: Float?, myFloatArray: [Float]?, myDouble: Double?, myDoubleArray: [Double]?, myString: String?, myStringArray: [String]?, myBytes: Data?, myBytesArray: [Data]?, myBoolean: Bool?, myBooleanArray: [Bool]?, myDate: Date?, myDateArray: [Date]?, myDateTime: Date?, myDateTimeArray: [Date]?, myFile: URL?, myFileArray: [URL]?, myUUID: UUID?, myUUIDArray: [UUID]?, myStringEnum: StringEnum?, myStringEnumArray: [StringEnum]?, myInlineStringEnum: MyInlineStringEnum?) { + self.myInteger = myInteger + self.myIntegerArray = myIntegerArray + self.myLong = myLong + self.myLongArray = myLongArray + self.myFloat = myFloat + self.myFloatArray = myFloatArray + self.myDouble = myDouble + self.myDoubleArray = myDoubleArray + self.myString = myString + self.myStringArray = myStringArray + self.myBytes = myBytes + self.myBytesArray = myBytesArray + self.myBoolean = myBoolean + self.myBooleanArray = myBooleanArray + self.myDate = myDate + self.myDateArray = myDateArray + self.myDateTime = myDateTime + self.myDateTimeArray = myDateTimeArray + self.myFile = myFile + self.myFileArray = myFileArray + self.myUUID = myUUID + self.myUUIDArray = myUUIDArray + self.myStringEnum = myStringEnum + self.myStringEnumArray = myStringEnumArray + self.myInlineStringEnum = myInlineStringEnum + } } diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/BaseCard.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/BaseCard.swift index 457b470ad344..a01eea070ce5 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/BaseCard.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/BaseCard.swift @@ -14,6 +14,9 @@ public struct BaseCard: Codable { public var cardType: String + public init(cardType: String) { + self.cardType = cardType + } } diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/ErrorInfo.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/ErrorInfo.swift index d0a816c0e95e..d89f5c361bb0 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/ErrorInfo.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/ErrorInfo.swift @@ -16,6 +16,11 @@ public struct ErrorInfo: Codable { public var message: String? public var details: [String]? + public init(code: Int?, message: String?, details: [String]?) { + self.code = code + self.message = message + self.details = details + } } diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/GetAllModelsResult.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/GetAllModelsResult.swift index cf69e76ab8cb..e079cdb618a3 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/GetAllModelsResult.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/GetAllModelsResult.swift @@ -16,6 +16,11 @@ public struct GetAllModelsResult: Codable { public var myPrimitive: AllPrimitives? public var myVariableNameTest: VariableNameTest? + public init(myPrimitiveArray: [AllPrimitives]?, myPrimitive: AllPrimitives?, myVariableNameTest: VariableNameTest?) { + self.myPrimitiveArray = myPrimitiveArray + self.myPrimitive = myPrimitive + self.myVariableNameTest = myVariableNameTest + } } diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/ModelWithPropertiesAndAdditionalProperties.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/ModelWithPropertiesAndAdditionalProperties.swift index b1768d129667..dac9f4a6e20d 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/ModelWithPropertiesAndAdditionalProperties.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/ModelWithPropertiesAndAdditionalProperties.swift @@ -21,6 +21,16 @@ public struct ModelWithPropertiesAndAdditionalProperties: Codable { public var myPrimitiveArrayReq: [AllPrimitives] public var myPrimitiveArrayOpt: [AllPrimitives]? + public init(myIntegerReq: Int, myIntegerOpt: Int?, myPrimitiveReq: AllPrimitives, myPrimitiveOpt: AllPrimitives?, myStringArrayReq: [String], myStringArrayOpt: [String]?, myPrimitiveArrayReq: [AllPrimitives], myPrimitiveArrayOpt: [AllPrimitives]?) { + self.myIntegerReq = myIntegerReq + self.myIntegerOpt = myIntegerOpt + self.myPrimitiveReq = myPrimitiveReq + self.myPrimitiveOpt = myPrimitiveOpt + self.myStringArrayReq = myStringArrayReq + self.myStringArrayOpt = myStringArrayOpt + self.myPrimitiveArrayReq = myPrimitiveArrayReq + self.myPrimitiveArrayOpt = myPrimitiveArrayOpt + } public var additionalProperties: [String:String] = [:] public subscript(key: String) -> String? { diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/PersonCard.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/PersonCard.swift index 9c5e70d56a1f..1159a7906161 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/PersonCard.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/PersonCard.swift @@ -16,6 +16,11 @@ public struct PersonCard: Codable { public var firstName: String? public var lastName: String? + public init(cardType: String, firstName: String?, lastName: String?) { + self.cardType = cardType + self.firstName = firstName + self.lastName = lastName + } } diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/PlaceCard.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/PlaceCard.swift index 3db208c0316e..71433da16ecb 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/PlaceCard.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/PlaceCard.swift @@ -16,6 +16,11 @@ public struct PlaceCard: Codable { public var placeName: String? public var placeAddress: String? + public init(cardType: String, placeName: String?, placeAddress: String?) { + self.cardType = cardType + self.placeName = placeName + self.placeAddress = placeAddress + } } diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/SampleBase.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/SampleBase.swift index 98af4ebd04c2..23a4da50337c 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/SampleBase.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/SampleBase.swift @@ -15,6 +15,10 @@ public struct SampleBase: Codable { public var baseClassStringProp: String? public var baseClassIntegerProp: Int? + public init(baseClassStringProp: String?, baseClassIntegerProp: Int?) { + self.baseClassStringProp = baseClassStringProp + self.baseClassIntegerProp = baseClassIntegerProp + } } diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/SampleSubClass.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/SampleSubClass.swift index 2556f6add6e5..672e781e6d72 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/SampleSubClass.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/SampleSubClass.swift @@ -17,6 +17,12 @@ public struct SampleSubClass: Codable { public var subClassStringProp: String? public var subClassIntegerProp: Int? + public init(baseClassStringProp: String?, baseClassIntegerProp: Int?, subClassStringProp: String?, subClassIntegerProp: Int?) { + self.baseClassStringProp = baseClassStringProp + self.baseClassIntegerProp = baseClassIntegerProp + self.subClassStringProp = subClassStringProp + self.subClassIntegerProp = subClassIntegerProp + } } diff --git a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/VariableNameTest.swift b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/VariableNameTest.swift index 975c92b306c2..dd47863042be 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/VariableNameTest.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/Swaggers/Models/VariableNameTest.swift @@ -19,6 +19,11 @@ public struct VariableNameTest: Codable { /** This model object property name should be unchanged from the JSON property name. */ public var normalName: String? + public init(exampleName: String?, _for: String?, normalName: String?) { + self.exampleName = exampleName + self._for = _for + self.normalName = normalName + } public enum CodingKeys: String, CodingKey { case exampleName = "example_name" diff --git a/samples/openapi3/client/petstore/php/.swagger-codegen-ignore b/samples/openapi3/client/petstore/php/.swagger-codegen-ignore new file mode 100644 index 000000000000..c5fa491b4c55 --- /dev/null +++ b/samples/openapi3/client/petstore/php/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/openapi3/client/petstore/php/.swagger-codegen/VERSION b/samples/openapi3/client/petstore/php/.swagger-codegen/VERSION new file mode 100644 index 000000000000..096bf47efe31 --- /dev/null +++ b/samples/openapi3/client/petstore/php/.swagger-codegen/VERSION @@ -0,0 +1 @@ +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/.php_cs b/samples/openapi3/client/petstore/php/SwaggerClient-php/.php_cs new file mode 100644 index 000000000000..6b8e23c818a9 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/.php_cs @@ -0,0 +1,18 @@ +level(Symfony\CS\FixerInterface::PSR2_LEVEL) + ->setUsingCache(true) + ->fixers( + [ + 'ordered_use', + 'phpdoc_order', + 'short_array_syntax', + 'strict', + 'strict_param' + ] + ) + ->finder( + Symfony\CS\Finder\DefaultFinder::create() + ->in(__DIR__) + ); diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/.travis.yml b/samples/openapi3/client/petstore/php/SwaggerClient-php/.travis.yml new file mode 100644 index 000000000000..d77f3825f6fe --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/.travis.yml @@ -0,0 +1,10 @@ +language: php +sudo: false +php: + - 5.4 + - 5.5 + - 5.6 + - 7.0 + - hhvm +before_install: "composer install" +script: "vendor/bin/phpunit" diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/README.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/README.md new file mode 100644 index 000000000000..953b70f1c8dd --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/README.md @@ -0,0 +1,189 @@ +# SwaggerClient-php +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PhpClientCodegen + +## Requirements + +PHP 5.5 and later + +## Installation & Usage +### Composer + +To install the bindings via [Composer](http://getcomposer.org/), add the following to `composer.json`: + +``` +{ + "repositories": [ + { + "type": "git", + "url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git" + } + ], + "require": { + "GIT_USER_ID/GIT_REPO_ID": "*@dev" + } +} +``` + +Then run `composer install` + +### Manual Installation + +Download the files and include `autoload.php`: + +```php + require_once('/path/to/SwaggerClient-php/vendor/autoload.php'); +``` + +## Tests + +To run the unit tests: + +``` +composer install +./vendor/bin/phpunit +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```php +testSpecialTags($client); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling AnotherFakeApi->testSpecialTags: ', $e->getMessage(), PHP_EOL; +} + +?> +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**testSpecialTags**](docs/Api/AnotherFakeApi.md#testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*FakeApi* | [**fakeOuterBooleanSerialize**](docs/Api/FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +*FakeApi* | [**fakeOuterCompositeSerialize**](docs/Api/FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +*FakeApi* | [**fakeOuterNumberSerialize**](docs/Api/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | +*FakeApi* | [**fakeOuterStringSerialize**](docs/Api/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | +*FakeApi* | [**testClientModel**](docs/Api/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**testEndpointParameters**](docs/Api/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumParameters**](docs/Api/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**testInlineAdditionalProperties**](docs/Api/FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**testJsonFormData**](docs/Api/FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123Api* | [**testClassname**](docs/Api/FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**addPet**](docs/Api/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/Api/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/Api/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/Api/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/Api/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/Api/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/Api/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/Api/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/Api/StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/Api/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/Api/StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/Api/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/Api/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/Api/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/Api/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/Api/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/Api/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/Api/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/Api/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/Api/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + +## Documentation For Models + + - [AdditionalPropertiesClass](docs/Model/AdditionalPropertiesClass.md) + - [Animal](docs/Model/Animal.md) + - [AnimalFarm](docs/Model/AnimalFarm.md) + - [ApiResponse](docs/Model/ApiResponse.md) + - [ArrayOfArrayOfNumberOnly](docs/Model/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/Model/ArrayOfNumberOnly.md) + - [ArrayTest](docs/Model/ArrayTest.md) + - [Body4](docs/Model/Body4.md) + - [Capitalization](docs/Model/Capitalization.md) + - [Cat](docs/Model/Cat.md) + - [Category](docs/Model/Category.md) + - [ClassModel](docs/Model/ClassModel.md) + - [Client](docs/Model/Client.md) + - [Dog](docs/Model/Dog.md) + - [EnumArrays](docs/Model/EnumArrays.md) + - [EnumClass](docs/Model/EnumClass.md) + - [EnumTest](docs/Model/EnumTest.md) + - [FormatTest](docs/Model/FormatTest.md) + - [HasOnlyReadOnly](docs/Model/HasOnlyReadOnly.md) + - [MapTest](docs/Model/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/Model/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model/Model200Response.md) + - [ModelList](docs/Model/ModelList.md) + - [ModelReturn](docs/Model/ModelReturn.md) + - [Name](docs/Model/Name.md) + - [NumberOnly](docs/Model/NumberOnly.md) + - [Order](docs/Model/Order.md) + - [OuterBoolean](docs/Model/OuterBoolean.md) + - [OuterComposite](docs/Model/OuterComposite.md) + - [OuterEnum](docs/Model/OuterEnum.md) + - [OuterNumber](docs/Model/OuterNumber.md) + - [OuterString](docs/Model/OuterString.md) + - [Pet](docs/Model/Pet.md) + - [ReadOnlyFirst](docs/Model/ReadOnlyFirst.md) + - [SpecialModelName_](docs/Model/SpecialModelName_.md) + - [Tag](docs/Model/Tag.md) + - [User](docs/Model/User.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +## api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + +## http_basic_test + +- **Type**: HTTP basic authentication + +## petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + + +## Author + +apiteam@swagger.io + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/composer.json b/samples/openapi3/client/petstore/php/SwaggerClient-php/composer.json new file mode 100644 index 000000000000..2ebbe805eea4 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/composer.json @@ -0,0 +1,36 @@ +{ + "name": "GIT_USER_ID/GIT_REPO_ID", + "description": "", + "keywords": [ + "swagger", + "php", + "sdk", + "api" + ], + "homepage": "http://swagger.io", + "license": "proprietary", + "authors": [ + { + "name": "Swagger and contributors", + "homepage": "https://github.com/swagger-api/swagger-codegen" + } + ], + "require": { + "php": ">=5.5", + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "guzzlehttp/guzzle": "^6.2" + }, + "require-dev": { + "phpunit/phpunit": "^4.8", + "squizlabs/php_codesniffer": "~2.6", + "friendsofphp/php-cs-fixer": "~1.12" + }, + "autoload": { + "psr-4": { "Swagger\\Client\\" : "lib/" } + }, + "autoload-dev": { + "psr-4": { "Swagger\\Client\\" : "test/" } + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/AnotherFakeApi.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/AnotherFakeApi.md new file mode 100644 index 000000000000..668341b0e2c3 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/AnotherFakeApi.md @@ -0,0 +1,58 @@ +# Swagger\Client\AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testSpecialTags**](AnotherFakeApi.md#testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags + + +# **testSpecialTags** +> \Swagger\Client\Model\Client testSpecialTags($client) + +To test special tags + +To test special tags + +### Example +```php +testSpecialTags($client); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling AnotherFakeApi->testSpecialTags: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](../Model/Client.md)| client model | + +### Return type + +[**\Swagger\Client\Model\Client**](../Model/Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md new file mode 100644 index 000000000000..d7ae0b50611d --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md @@ -0,0 +1,497 @@ +# Swagger\Client\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 | +[**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** +> \Swagger\Client\Model\OuterBoolean fakeOuterBooleanSerialize($body) + + + +Test serialization of outer boolean types + +### Example +```php +fakeOuterBooleanSerialize($body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->fakeOuterBooleanSerialize: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **bool**| Input boolean as post body | [optional] + +### Return type + +[**\Swagger\Client\Model\OuterBoolean**](../Model/OuterBoolean.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **fakeOuterCompositeSerialize** +> \Swagger\Client\Model\OuterComposite fakeOuterCompositeSerialize($outer_composite) + + + +Test serialization of object with outer number type + +### Example +```php +fakeOuterCompositeSerialize($outer_composite); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->fakeOuterCompositeSerialize: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **outer_composite** | [**OuterComposite**](../Model/OuterComposite.md)| Input composite as post body | [optional] + +### Return type + +[**\Swagger\Client\Model\OuterComposite**](../Model/OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **fakeOuterNumberSerialize** +> \Swagger\Client\Model\OuterNumber fakeOuterNumberSerialize($body) + + + +Test serialization of outer number types + +### Example +```php +fakeOuterNumberSerialize($body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->fakeOuterNumberSerialize: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **float**| Input number as post body | [optional] + +### Return type + +[**\Swagger\Client\Model\OuterNumber**](../Model/OuterNumber.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **fakeOuterStringSerialize** +> \Swagger\Client\Model\OuterString fakeOuterStringSerialize($body) + + + +Test serialization of outer string types + +### Example +```php +fakeOuterStringSerialize($body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->fakeOuterStringSerialize: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **string**| Input string as post body | [optional] + +### Return type + +[**\Swagger\Client\Model\OuterString**](../Model/OuterString.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **testClientModel** +> \Swagger\Client\Model\Client testClientModel($client) + +To test \"client\" model + +To test \"client\" model + +### Example +```php +testClientModel($client); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->testClientModel: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](../Model/Client.md)| client model | + +### Return type + +[**\Swagger\Client\Model\Client**](../Model/Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **testEndpointParameters** +> testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```php +setUsername('YOUR_USERNAME') + ->setPassword('YOUR_PASSWORD'); + + +$apiInstance = new Swagger\Client\Api\FakeApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$number = 3.4; // float | None +$double = 3.4; // double | None +$pattern_without_delimiter = "pattern_without_delimiter_example"; // string | None +$byte = "byte_example"; // string | None +$integer = 56; // int | None +$int32 = 56; // int | None +$int64 = 56; // int | None +$float = 3.4; // float | None +$string = "string_example"; // string | None +$binary = "/path/to/file.txt"; // \SplFileObject | None +$date = new \DateTime("2013-10-20T19:20:30+01:00"); // \DateTime | None +$date_time = new \DateTime("2013-10-20T19:20:30+01:00"); // \DateTime | None +$password = "password_example"; // string | None +$callback = "callback_example"; // string | None + +try { + $apiInstance->testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **float**| None | + **double** | **double**| None | + **pattern_without_delimiter** | **string**| None | + **byte** | **string**| None | + **integer** | **int**| None | [optional] + **int32** | **int**| None | [optional] + **int64** | **int**| None | [optional] + **float** | **float**| None | [optional] + **string** | **string**| None | [optional] + **binary** | **\SplFileObject****\SplFileObject**| None | [optional] + **date** | **\DateTime**| None | [optional] + **date_time** | **\DateTime**| None | [optional] + **password** | **string**| None | [optional] + **callback** | **string**| None | [optional] + +### Return type + +void (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 + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **testEnumParameters** +> testEnumParameters($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_form_string_array, $enum_form_string) + +To test enum parameters + +To test enum parameters + +### Example +```php +testEnumParameters($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_form_string_array, $enum_form_string); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->testEnumParameters: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enum_header_string_array** | [**string[]**](../Model/string.md)| Header parameter enum test (string array) | [optional] + **enum_header_string** | **string**| Header parameter enum test (string) | [optional] + **enum_query_string_array** | [**string[]**](../Model/string.md)| Query parameter enum test (string array) | [optional] + **enum_query_string** | **string**| Query parameter enum test (string) | [optional] + **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] + **enum_query_double** | **double**| Query parameter enum test (double) | [optional] + **enum_form_string_array** | [**string[]**](../Model/array.md)| Form parameter enum test (string array) | [optional] + **enum_form_string** | **string**| Form parameter enum test (string) | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties($unknown_base_type) + +test inline additionalProperties + +### Example +```php +testInlineAdditionalProperties($unknown_base_type); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->testInlineAdditionalProperties: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **unknown_base_type** | [**map[string,string]**](../Model/UNKNOWN_BASE_TYPE.md)| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **testJsonFormData** +> testJsonFormData($body4) + +test json serialization of form data + +### Example +```php +testJsonFormData($body4); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->testJsonFormData: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body4** | [**Body4**](../Model/Body4.md)| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/FakeClassnameTags123Api.md new file mode 100644 index 000000000000..6314df1bc73c --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/FakeClassnameTags123Api.md @@ -0,0 +1,64 @@ +# Swagger\Client\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** +> \Swagger\Client\Model\Client testClassname($client) + +To test class name in snake case + +To test class name in snake case + +### Example +```php +setApiKey('api_key_query', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key_query', 'Bearer'); + +$apiInstance = new Swagger\Client\Api\FakeClassnameTags123Api( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$client = new \Swagger\Client\Model\Client(); // Client | client model + +try { + $result = $apiInstance->testClassname($client); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling FakeClassnameTags123Api->testClassname: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](../Model/Client.md)| client model | + +### Return type + +[**\Swagger\Client\Model\Client**](../Model/Client.md) + +### Authorization + +[api_key_query](../../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md new file mode 100644 index 000000000000..7f2722307182 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md @@ -0,0 +1,438 @@ +# Swagger\Client\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 + + +# **addPet** +> addPet($pet) + +Add a new pet to the store + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$pet = new \Swagger\Client\Model\Pet(); // Pet | Pet object that needs to be added to the store + +try { + $apiInstance->addPet($pet); +} catch (Exception $e) { + echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **deletePet** +> deletePet($pet_id, $api_key) + +Deletes a pet + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$pet_id = 789; // int | Pet id to delete +$api_key = "api_key_example"; // string | + +try { + $apiInstance->deletePet($pet_id, $api_key); +} catch (Exception $e) { + echo 'Exception when calling PetApi->deletePet: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| Pet id to delete | + **api_key** | **string**| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **findPetsByStatus** +> \Swagger\Client\Model\Pet[] findPetsByStatus($status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$status = array("status_example"); // string[] | Status values that need to be considered for filter + +try { + $result = $apiInstance->findPetsByStatus($status); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->findPetsByStatus: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**string[]**](../Model/string.md)| Status values that need to be considered for filter | + +### Return type + +[**\Swagger\Client\Model\Pet[]**](../Model/Pet.md) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **findPetsByTags** +> \Swagger\Client\Model\Pet[] findPetsByTags($tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$tags = array("tags_example"); // string[] | Tags to filter by + +try { + $result = $apiInstance->findPetsByTags($tags); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->findPetsByTags: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**string[]**](../Model/string.md)| Tags to filter by | + +### Return type + +[**\Swagger\Client\Model\Pet[]**](../Model/Pet.md) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **getPetById** +> \Swagger\Client\Model\Pet getPetById($pet_id) + +Find pet by ID + +Returns a single pet + +### Example +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$pet_id = 789; // int | ID of pet to return + +try { + $result = $apiInstance->getPetById($pet_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->getPetById: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet to return | + +### Return type + +[**\Swagger\Client\Model\Pet**](../Model/Pet.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **updatePet** +> updatePet($pet) + +Update an existing pet + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$pet = new \Swagger\Client\Model\Pet(); // Pet | Pet object that needs to be added to the store + +try { + $apiInstance->updatePet($pet); +} catch (Exception $e) { + echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **updatePetWithForm** +> updatePetWithForm($pet_id, $name, $status) + +Updates a pet in the store with form data + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$pet_id = 789; // int | ID of pet that needs to be updated +$name = "name_example"; // string | Updated name of the pet +$status = "status_example"; // string | Updated status of the pet + +try { + $apiInstance->updatePetWithForm($pet_id, $name, $status); +} catch (Exception $e) { + echo 'Exception when calling PetApi->updatePetWithForm: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet that needs to be updated | + **name** | **string**| Updated name of the pet | [optional] + **status** | **string**| Updated status of the pet | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **uploadFile** +> \Swagger\Client\Model\ApiResponse uploadFile($pet_id, $additional_metadata, $file) + +uploads an image + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$pet_id = 789; // int | ID of pet to update +$additional_metadata = "additional_metadata_example"; // string | Additional data to pass to server +$file = "/path/to/file.txt"; // \SplFileObject | file to upload + +try { + $result = $apiInstance->uploadFile($pet_id, $additional_metadata, $file); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->uploadFile: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet to update | + **additional_metadata** | **string**| Additional data to pass to server | [optional] + **file** | **\SplFileObject****\SplFileObject**| file to upload | [optional] + +### Return type + +[**\Swagger\Client\Model\ApiResponse**](../Model/ApiResponse.md) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md new file mode 100644 index 000000000000..1b1f88a006e4 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md @@ -0,0 +1,207 @@ +# Swagger\Client\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($order_id) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```php +deleteOrder($order_id); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->deleteOrder: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **string**| ID of the order that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **getInventory** +> map[string,int] getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + +$apiInstance = new Swagger\Client\Api\StoreApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); + +try { + $result = $apiInstance->getInventory(); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->getInventory: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**map[string,int]** + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **getOrderById** +> \Swagger\Client\Model\Order getOrderById($order_id) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```php +getOrderById($order_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->getOrderById: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **int**| ID of pet that needs to be fetched | + +### Return type + +[**\Swagger\Client\Model\Order**](../Model/Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **placeOrder** +> \Swagger\Client\Model\Order placeOrder($order) + +Place an order for a pet + +### Example +```php +placeOrder($order); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->placeOrder: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order** | [**Order**](../Model/Order.md)| order placed for purchasing the pet | + +### Return type + +[**\Swagger\Client\Model\Order**](../Model/Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md new file mode 100644 index 000000000000..a4f2313aba9c --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md @@ -0,0 +1,392 @@ +# Swagger\Client\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 +```php +createUser($user); +} catch (Exception $e) { + echo 'Exception when calling UserApi->createUser: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**User**](../Model/User.md)| Created user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **createUsersWithArrayInput** +> createUsersWithArrayInput($user) + +Creates list of users with given input array + +### Example +```php +createUsersWithArrayInput($user); +} catch (Exception $e) { + echo 'Exception when calling UserApi->createUsersWithArrayInput: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**\Swagger\Client\Model\User[]**](../Model/User.md)| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **createUsersWithListInput** +> createUsersWithListInput($user) + +Creates list of users with given input array + +### Example +```php +createUsersWithListInput($user); +} catch (Exception $e) { + echo 'Exception when calling UserApi->createUsersWithListInput: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**\Swagger\Client\Model\User[]**](../Model/User.md)| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **deleteUser** +> deleteUser($username) + +Delete user + +This can only be done by the logged in user. + +### Example +```php +deleteUser($username); +} catch (Exception $e) { + echo 'Exception when calling UserApi->deleteUser: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **getUserByName** +> \Swagger\Client\Model\User getUserByName($username) + +Get user by user name + +### Example +```php +getUserByName($username); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UserApi->getUserByName: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**\Swagger\Client\Model\User**](../Model/User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **loginUser** +> string loginUser($username, $password) + +Logs user into the system + +### Example +```php +loginUser($username, $password); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UserApi->loginUser: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### 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 + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + +### Example +```php +logoutUser(); +} catch (Exception $e) { + echo 'Exception when calling UserApi->logoutUser: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **updateUser** +> updateUser($username, $user) + +Updated user + +This can only be done by the logged in user. + +### Example +```php +updateUser($username, $user); +} catch (Exception $e) { + echo 'Exception when calling UserApi->updateUser: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| name that need to be deleted | + **user** | [**User**](../Model/User.md)| Updated user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/AdditionalPropertiesClass.md new file mode 100644 index 000000000000..b162fe9595fb --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**map_property** | **map[string,string]** | | [optional] +**map_of_map_property** | [**map[string,map[string,string]]**](map.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Animal.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Animal.md new file mode 100644 index 000000000000..c57fbe8ea4aa --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Animal.md @@ -0,0 +1,11 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **string** | | +**color** | **string** | | [optional] [default to 'red'] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/AnimalFarm.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/AnimalFarm.md new file mode 100644 index 000000000000..df6bab21dae8 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/AnimalFarm.md @@ -0,0 +1,9 @@ +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ApiResponse.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ApiResponse.md new file mode 100644 index 000000000000..9d3511834227 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ApiResponse.md @@ -0,0 +1,12 @@ +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **int** | | [optional] +**type** | **string** | | [optional] +**message** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 000000000000..7831e1898882 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_array_number** | [**float[][]**](array.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ArrayOfNumberOnly.md new file mode 100644 index 000000000000..a32607e42012 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_number** | **float[]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ArrayTest.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ArrayTest.md new file mode 100644 index 000000000000..f982dc2e4c7c --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ArrayTest.md @@ -0,0 +1,12 @@ +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_of_string** | **string[]** | | [optional] +**array_array_of_integer** | [**int[][]**](array.md) | | [optional] +**array_array_of_model** | [**\Swagger\Client\Model\ReadOnlyFirst[][]**](array.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body.md new file mode 100644 index 000000000000..c3cbc85ee899 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body.md @@ -0,0 +1,11 @@ +# Body + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **string** | Updated name of the pet | [optional] +**status** | **string** | Updated status of the pet | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body1.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body1.md new file mode 100644 index 000000000000..eb0f5e3d2163 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body1.md @@ -0,0 +1,11 @@ +# Body1 + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**additional_metadata** | **string** | Additional data to pass to server | [optional] +**file** | **string** | file to upload | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body2.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body2.md new file mode 100644 index 000000000000..5afe5ce7313c --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body2.md @@ -0,0 +1,11 @@ +# Body2 + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_form_string_array** | **string[]** | Form parameter enum test (string array) | [optional] +**enum_form_string** | **string** | Form parameter enum test (string) | [optional] [default to '-efg'] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body3.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body3.md new file mode 100644 index 000000000000..ff7e075180f5 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body3.md @@ -0,0 +1,23 @@ +# Body3 + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **int** | None | [optional] +**int32** | **int** | None | [optional] +**int64** | **int** | None | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | None | +**float** | **float** | None | [optional] +**double** | **double** | None | +**string** | **string** | None | [optional] +**pattern_without_delimiter** | **string** | None | +**byte** | **string** | None | +**binary** | **string** | None | [optional] +**date** | [**\DateTime**](\DateTime.md) | None | [optional] +**date_time** | [**\DateTime**](\DateTime.md) | None | [optional] +**password** | **string** | None | [optional] +**callback** | **string** | None | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body4.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body4.md new file mode 100644 index 000000000000..f583ce67bec3 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Body4.md @@ -0,0 +1,11 @@ +# Body4 + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**param** | **string** | field1 | +**param2** | **string** | field2 | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Capitalization.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Capitalization.md new file mode 100644 index 000000000000..0fcc9e873d71 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Capitalization.md @@ -0,0 +1,15 @@ +# Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**small_camel** | **string** | | [optional] +**capital_camel** | **string** | | [optional] +**small_snake** | **string** | | [optional] +**capital_snake** | **string** | | [optional] +**sca_eth_flow_points** | **string** | | [optional] +**att_name** | **string** | Name of the pet | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Cat.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Cat.md new file mode 100644 index 000000000000..8d30565d014e --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Cat.md @@ -0,0 +1,10 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Category.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Category.md new file mode 100644 index 000000000000..80aef312e5e6 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ClassModel.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ClassModel.md new file mode 100644 index 000000000000..3ad025b6ed3a --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ClassModel.md @@ -0,0 +1,10 @@ +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Client.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Client.md new file mode 100644 index 000000000000..f6047a624710 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Dog.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Dog.md new file mode 100644 index 000000000000..3c04bdf4cf70 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Dog.md @@ -0,0 +1,10 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/EnumArrays.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/EnumArrays.md new file mode 100644 index 000000000000..ebaedecdae0e --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/EnumArrays.md @@ -0,0 +1,11 @@ +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**just_symbol** | **string** | | [optional] +**array_enum** | **string[]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/EnumClass.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/EnumClass.md new file mode 100644 index 000000000000..67f017becd0c --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/EnumClass.md @@ -0,0 +1,9 @@ +# EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/EnumTest.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/EnumTest.md new file mode 100644 index 000000000000..9d0911aa9385 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/EnumTest.md @@ -0,0 +1,14 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_string** | **string** | | [optional] +**enum_string_required** | **string** | | +**enum_integer** | **int** | | [optional] +**enum_number** | **double** | | [optional] +**outer_enum** | [**\Swagger\Client\Model\OuterEnum**](OuterEnum.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/FormatTest.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/FormatTest.md new file mode 100644 index 000000000000..e106ff1eba2e --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/FormatTest.md @@ -0,0 +1,22 @@ +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **int** | | [optional] +**int32** | **int** | | [optional] +**int64** | **int** | | [optional] +**number** | **float** | | +**float** | **float** | | [optional] +**double** | **double** | | [optional] +**string** | **string** | | [optional] +**byte** | **string** | | +**binary** | [**\SplFileObject**](\SplFileObject.md) | | [optional] +**date** | [**\DateTime**](\DateTime.md) | | +**date_time** | [**\DateTime**](\DateTime.md) | | [optional] +**uuid** | **string** | | [optional] +**password** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/HasOnlyReadOnly.md new file mode 100644 index 000000000000..5e64572b781d --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **string** | | [optional] +**foo** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/MapTest.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/MapTest.md new file mode 100644 index 000000000000..e2781ccc398a --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/MapTest.md @@ -0,0 +1,11 @@ +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**map_map_of_string** | [**map[string,map[string,string]]**](map.md) | | [optional] +**map_of_enum_string** | **map[string,string]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 000000000000..1e3c4f7bfe12 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **string** | | [optional] +**date_time** | [**\DateTime**](\DateTime.md) | | [optional] +**map** | [**map[string,\Swagger\Client\Model\Animal]**](Animal.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Model200Response.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Model200Response.md new file mode 100644 index 000000000000..ebbea5c68af1 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Model200Response.md @@ -0,0 +1,11 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | [optional] +**class** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ModelList.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ModelList.md new file mode 100644 index 000000000000..e18ba4e123df --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ModelList.md @@ -0,0 +1,10 @@ +# ModelList + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123_list** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ModelReturn.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ModelReturn.md new file mode 100644 index 000000000000..9adb62e1e121 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ModelReturn.md @@ -0,0 +1,10 @@ +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**return** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Name.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Name.md new file mode 100644 index 000000000000..4565647e1ef6 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | +**snake_case** | **int** | | [optional] +**property** | **string** | | [optional] +**_123_number** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/NumberOnly.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/NumberOnly.md new file mode 100644 index 000000000000..93a0fde7b931 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/NumberOnly.md @@ -0,0 +1,10 @@ +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**just_number** | **float** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Order.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Order.md new file mode 100644 index 000000000000..ddae5cc2b571 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**pet_id** | **int** | | [optional] +**quantity** | **int** | | [optional] +**ship_date** | [**\DateTime**](\DateTime.md) | | [optional] +**status** | **string** | Order Status | [optional] +**complete** | **bool** | | [optional] [default to false] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterBoolean.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterBoolean.md new file mode 100644 index 000000000000..8b2433994745 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterBoolean.md @@ -0,0 +1,9 @@ +# OuterBoolean + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterComposite.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterComposite.md new file mode 100644 index 000000000000..8f791968a370 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterComposite.md @@ -0,0 +1,12 @@ +# OuterComposite + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**my_number** | [**\Swagger\Client\Model\OuterNumber**](OuterNumber.md) | | [optional] +**my_string** | [**\Swagger\Client\Model\OuterString**](OuterString.md) | | [optional] +**my_boolean** | [**\Swagger\Client\Model\OuterBoolean**](OuterBoolean.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterEnum.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterEnum.md new file mode 100644 index 000000000000..06d413b01680 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterEnum.md @@ -0,0 +1,9 @@ +# OuterEnum + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterNumber.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterNumber.md new file mode 100644 index 000000000000..8aa37f329bd4 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterNumber.md @@ -0,0 +1,9 @@ +# OuterNumber + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterString.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterString.md new file mode 100644 index 000000000000..9ccaadaf98df --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/OuterString.md @@ -0,0 +1,9 @@ +# OuterString + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Pet.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Pet.md new file mode 100644 index 000000000000..4525fe7d7767 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**category** | [**\Swagger\Client\Model\Category**](Category.md) | | [optional] +**name** | **string** | | +**photo_urls** | **string[]** | | +**tags** | [**\Swagger\Client\Model\Tag[]**](Tag.md) | | [optional] +**status** | **string** | pet status in the store | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ReadOnlyFirst.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ReadOnlyFirst.md new file mode 100644 index 000000000000..90662a00cf32 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **string** | | [optional] +**baz** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/SpecialModelName_.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/SpecialModelName_.md new file mode 100644 index 000000000000..a3c3c3412c93 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/SpecialModelName_.md @@ -0,0 +1,10 @@ +# SpecialModelName_ + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**special_property_name** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Tag.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Tag.md new file mode 100644 index 000000000000..15ec3e0a91df --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/User.md b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/User.md new file mode 100644 index 000000000000..ff278fd4889e --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/docs/Model/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**username** | **string** | | [optional] +**first_name** | **string** | | [optional] +**last_name** | **string** | | [optional] +**email** | **string** | | [optional] +**password** | **string** | | [optional] +**phone** | **string** | | [optional] +**user_status** | **int** | User Status | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/git_push.sh b/samples/openapi3/client/petstore/php/SwaggerClient-php/git_push.sh new file mode 100644 index 000000000000..160f6f213999 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/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 swagger-petstore-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/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/AnotherFakeApi.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/AnotherFakeApi.php new file mode 100644 index 000000000000..274c96ea0022 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/AnotherFakeApi.php @@ -0,0 +1,365 @@ +client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation testSpecialTags + * + * To test special tags + * + * @param Client $client client model (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\Client + */ + public function testSpecialTags($client) + { + list($response) = $this->testSpecialTagsWithHttpInfo($client); + return $response; + } + + /** + * Operation testSpecialTagsWithHttpInfo + * + * To test special tags + * + * @param Client $client client model (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) + */ + public function testSpecialTagsWithHttpInfo($client) + { + $returnType = '\Swagger\Client\Model\Client'; + $request = $this->testSpecialTagsRequest($client); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\Client', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation testSpecialTagsAsync + * + * To test special tags + * + * @param Client $client client model (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testSpecialTagsAsync($client) + { + return $this->testSpecialTagsAsyncWithHttpInfo($client) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testSpecialTagsAsyncWithHttpInfo + * + * To test special tags + * + * @param Client $client client model (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testSpecialTagsAsyncWithHttpInfo($client) + { + $returnType = '\Swagger\Client\Model\Client'; + $request = $this->testSpecialTagsRequest($client); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testSpecialTags' + * + * @param Client $client client model (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function testSpecialTagsRequest($client) + { + // verify the required parameter 'client' is set + if ($client === null || (is_array($client) && count($client) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $client when calling testSpecialTags' + ); + } + + $resourcePath = '/another-fake/dummy'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($client)) { + $_tempBody = $client; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'PATCH', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php new file mode 100644 index 000000000000..8d0f582727cf --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -0,0 +1,2471 @@ +client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation fakeOuterBooleanSerialize + * + * @param bool $body Input boolean as post body (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\OuterBoolean + */ + public function fakeOuterBooleanSerialize($body = null) + { + list($response) = $this->fakeOuterBooleanSerializeWithHttpInfo($body); + return $response; + } + + /** + * Operation fakeOuterBooleanSerializeWithHttpInfo + * + * @param bool $body Input boolean as post body (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\OuterBoolean, HTTP status code, HTTP response headers (array of strings) + */ + public function fakeOuterBooleanSerializeWithHttpInfo($body = null) + { + $returnType = '\Swagger\Client\Model\OuterBoolean'; + $request = $this->fakeOuterBooleanSerializeRequest($body); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\OuterBoolean', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation fakeOuterBooleanSerializeAsync + * + * + * + * @param bool $body Input boolean as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function fakeOuterBooleanSerializeAsync($body = null) + { + return $this->fakeOuterBooleanSerializeAsyncWithHttpInfo($body) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation fakeOuterBooleanSerializeAsyncWithHttpInfo + * + * + * + * @param bool $body Input boolean as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function fakeOuterBooleanSerializeAsyncWithHttpInfo($body = null) + { + $returnType = '\Swagger\Client\Model\OuterBoolean'; + $request = $this->fakeOuterBooleanSerializeRequest($body); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'fakeOuterBooleanSerialize' + * + * @param bool $body Input boolean as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function fakeOuterBooleanSerializeRequest($body = null) + { + + $resourcePath = '/fake/outer/boolean'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['*/*'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['*/*'], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation fakeOuterCompositeSerialize + * + * @param OuterComposite $outer_composite Input composite as post body (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\OuterComposite + */ + public function fakeOuterCompositeSerialize($outer_composite = null) + { + list($response) = $this->fakeOuterCompositeSerializeWithHttpInfo($outer_composite); + return $response; + } + + /** + * Operation fakeOuterCompositeSerializeWithHttpInfo + * + * @param OuterComposite $outer_composite Input composite as post body (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\OuterComposite, HTTP status code, HTTP response headers (array of strings) + */ + public function fakeOuterCompositeSerializeWithHttpInfo($outer_composite = null) + { + $returnType = '\Swagger\Client\Model\OuterComposite'; + $request = $this->fakeOuterCompositeSerializeRequest($outer_composite); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\OuterComposite', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation fakeOuterCompositeSerializeAsync + * + * + * + * @param OuterComposite $outer_composite Input composite as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function fakeOuterCompositeSerializeAsync($outer_composite = null) + { + return $this->fakeOuterCompositeSerializeAsyncWithHttpInfo($outer_composite) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation fakeOuterCompositeSerializeAsyncWithHttpInfo + * + * + * + * @param OuterComposite $outer_composite Input composite as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function fakeOuterCompositeSerializeAsyncWithHttpInfo($outer_composite = null) + { + $returnType = '\Swagger\Client\Model\OuterComposite'; + $request = $this->fakeOuterCompositeSerializeRequest($outer_composite); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'fakeOuterCompositeSerialize' + * + * @param OuterComposite $outer_composite Input composite as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function fakeOuterCompositeSerializeRequest($outer_composite = null) + { + + $resourcePath = '/fake/outer/composite'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($outer_composite)) { + $_tempBody = $outer_composite; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['*/*'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['*/*'], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation fakeOuterNumberSerialize + * + * @param float $body Input number as post body (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\OuterNumber + */ + public function fakeOuterNumberSerialize($body = null) + { + list($response) = $this->fakeOuterNumberSerializeWithHttpInfo($body); + return $response; + } + + /** + * Operation fakeOuterNumberSerializeWithHttpInfo + * + * @param float $body Input number as post body (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\OuterNumber, HTTP status code, HTTP response headers (array of strings) + */ + public function fakeOuterNumberSerializeWithHttpInfo($body = null) + { + $returnType = '\Swagger\Client\Model\OuterNumber'; + $request = $this->fakeOuterNumberSerializeRequest($body); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\OuterNumber', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation fakeOuterNumberSerializeAsync + * + * + * + * @param float $body Input number as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function fakeOuterNumberSerializeAsync($body = null) + { + return $this->fakeOuterNumberSerializeAsyncWithHttpInfo($body) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation fakeOuterNumberSerializeAsyncWithHttpInfo + * + * + * + * @param float $body Input number as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function fakeOuterNumberSerializeAsyncWithHttpInfo($body = null) + { + $returnType = '\Swagger\Client\Model\OuterNumber'; + $request = $this->fakeOuterNumberSerializeRequest($body); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'fakeOuterNumberSerialize' + * + * @param float $body Input number as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function fakeOuterNumberSerializeRequest($body = null) + { + + $resourcePath = '/fake/outer/number'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['*/*'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['*/*'], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation fakeOuterStringSerialize + * + * @param string $body Input string as post body (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\OuterString + */ + public function fakeOuterStringSerialize($body = null) + { + list($response) = $this->fakeOuterStringSerializeWithHttpInfo($body); + return $response; + } + + /** + * Operation fakeOuterStringSerializeWithHttpInfo + * + * @param string $body Input string as post body (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\OuterString, HTTP status code, HTTP response headers (array of strings) + */ + public function fakeOuterStringSerializeWithHttpInfo($body = null) + { + $returnType = '\Swagger\Client\Model\OuterString'; + $request = $this->fakeOuterStringSerializeRequest($body); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\OuterString', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation fakeOuterStringSerializeAsync + * + * + * + * @param string $body Input string as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function fakeOuterStringSerializeAsync($body = null) + { + return $this->fakeOuterStringSerializeAsyncWithHttpInfo($body) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation fakeOuterStringSerializeAsyncWithHttpInfo + * + * + * + * @param string $body Input string as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function fakeOuterStringSerializeAsyncWithHttpInfo($body = null) + { + $returnType = '\Swagger\Client\Model\OuterString'; + $request = $this->fakeOuterStringSerializeRequest($body); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'fakeOuterStringSerialize' + * + * @param string $body Input string as post body (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function fakeOuterStringSerializeRequest($body = null) + { + + $resourcePath = '/fake/outer/string'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['*/*'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['*/*'], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation testClientModel + * + * To test \"client\" model + * + * @param Client $client client model (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\Client + */ + public function testClientModel($client) + { + list($response) = $this->testClientModelWithHttpInfo($client); + return $response; + } + + /** + * Operation testClientModelWithHttpInfo + * + * To test \"client\" model + * + * @param Client $client client model (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) + */ + public function testClientModelWithHttpInfo($client) + { + $returnType = '\Swagger\Client\Model\Client'; + $request = $this->testClientModelRequest($client); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\Client', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation testClientModelAsync + * + * To test \"client\" model + * + * @param Client $client client model (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testClientModelAsync($client) + { + return $this->testClientModelAsyncWithHttpInfo($client) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testClientModelAsyncWithHttpInfo + * + * To test \"client\" model + * + * @param Client $client client model (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testClientModelAsyncWithHttpInfo($client) + { + $returnType = '\Swagger\Client\Model\Client'; + $request = $this->testClientModelRequest($client); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testClientModel' + * + * @param Client $client client model (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function testClientModelRequest($client) + { + // verify the required parameter 'client' is set + if ($client === null || (is_array($client) && count($client) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $client when calling testClientModel' + ); + } + + $resourcePath = '/fake'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($client)) { + $_tempBody = $client; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'PATCH', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation testEndpointParameters + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @param float $number None (required) + * @param double $double None (required) + * @param string $pattern_without_delimiter None (required) + * @param string $byte None (required) + * @param int $integer None (optional) + * @param int $int32 None (optional) + * @param int $int64 None (optional) + * @param float $float None (optional) + * @param string $string None (optional) + * @param \SplFileObject $binary None (optional) + * @param \DateTime $date None (optional) + * @param \DateTime $date_time None (optional) + * @param string $password None (optional) + * @param string $callback None (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) + { + $this->testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); + } + + /** + * Operation testEndpointParametersWithHttpInfo + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @param float $number None (required) + * @param double $double None (required) + * @param string $pattern_without_delimiter None (required) + * @param string $byte None (required) + * @param int $integer None (optional) + * @param int $int32 None (optional) + * @param int $int64 None (optional) + * @param float $float None (optional) + * @param string $string None (optional) + * @param \SplFileObject $binary None (optional) + * @param \DateTime $date None (optional) + * @param \DateTime $date_time None (optional) + * @param string $password None (optional) + * @param string $callback None (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) + { + $returnType = ''; + $request = $this->testEndpointParametersRequest($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation testEndpointParametersAsync + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @param float $number None (required) + * @param double $double None (required) + * @param string $pattern_without_delimiter None (required) + * @param string $byte None (required) + * @param int $integer None (optional) + * @param int $int32 None (optional) + * @param int $int64 None (optional) + * @param float $float None (optional) + * @param string $string None (optional) + * @param \SplFileObject $binary None (optional) + * @param \DateTime $date None (optional) + * @param \DateTime $date_time None (optional) + * @param string $password None (optional) + * @param string $callback None (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testEndpointParametersAsync($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) + { + return $this->testEndpointParametersAsyncWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testEndpointParametersAsyncWithHttpInfo + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @param float $number None (required) + * @param double $double None (required) + * @param string $pattern_without_delimiter None (required) + * @param string $byte None (required) + * @param int $integer None (optional) + * @param int $int32 None (optional) + * @param int $int64 None (optional) + * @param float $float None (optional) + * @param string $string None (optional) + * @param \SplFileObject $binary None (optional) + * @param \DateTime $date None (optional) + * @param \DateTime $date_time None (optional) + * @param string $password None (optional) + * @param string $callback None (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testEndpointParametersAsyncWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) + { + $returnType = ''; + $request = $this->testEndpointParametersRequest($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testEndpointParameters' + * + * @param float $number None (required) + * @param double $double None (required) + * @param string $pattern_without_delimiter None (required) + * @param string $byte None (required) + * @param int $integer None (optional) + * @param int $int32 None (optional) + * @param int $int64 None (optional) + * @param float $float None (optional) + * @param string $string None (optional) + * @param \SplFileObject $binary None (optional) + * @param \DateTime $date None (optional) + * @param \DateTime $date_time None (optional) + * @param string $password None (optional) + * @param string $callback None (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function testEndpointParametersRequest($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) + { + // verify the required parameter 'number' is set + if ($number === null || (is_array($number) && count($number) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $number when calling testEndpointParameters' + ); + } + if ($number > 543.2) { + throw new \InvalidArgumentException('invalid value for "$number" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 543.2.'); + } + if ($number < 32.1) { + throw new \InvalidArgumentException('invalid value for "$number" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 32.1.'); + } + + // verify the required parameter 'double' is set + if ($double === null || (is_array($double) && count($double) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $double when calling testEndpointParameters' + ); + } + if ($double > 123.4) { + throw new \InvalidArgumentException('invalid value for "$double" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 123.4.'); + } + if ($double < 67.8) { + throw new \InvalidArgumentException('invalid value for "$double" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 67.8.'); + } + + // verify the required parameter 'pattern_without_delimiter' is set + if ($pattern_without_delimiter === null || (is_array($pattern_without_delimiter) && count($pattern_without_delimiter) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $pattern_without_delimiter when calling testEndpointParameters' + ); + } + // verify the required parameter 'byte' is set + if ($byte === null || (is_array($byte) && count($byte) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $byte when calling testEndpointParameters' + ); + } + if ($integer !== null && $integer > 100) { + throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 100.'); + } + if ($integer !== null && $integer < 10) { + throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); + } + + if ($int32 !== null && $int32 > 200) { + throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 200.'); + } + if ($int32 !== null && $int32 < 20) { + throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 20.'); + } + + if ($float !== null && $float > 987.6) { + throw new \InvalidArgumentException('invalid value for "$float" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 987.6.'); + } + + if ($password !== null && strlen($password) > 64) { + throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 64.'); + } + if ($password !== null && strlen($password) < 10) { + throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); + } + + + $resourcePath = '/fake'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // form params + if ($integer !== null) { + $formParams['integer'] = ObjectSerializer::toFormValue($integer); + } + // form params + if ($int32 !== null) { + $formParams['int32'] = ObjectSerializer::toFormValue($int32); + } + // form params + if ($int64 !== null) { + $formParams['int64'] = ObjectSerializer::toFormValue($int64); + } + // form params + if ($number !== null) { + $formParams['number'] = ObjectSerializer::toFormValue($number); + } + // form params + if ($float !== null) { + $formParams['float'] = ObjectSerializer::toFormValue($float); + } + // form params + if ($double !== null) { + $formParams['double'] = ObjectSerializer::toFormValue($double); + } + // form params + if ($string !== null) { + $formParams['string'] = ObjectSerializer::toFormValue($string); + } + // form params + if ($pattern_without_delimiter !== null) { + $formParams['pattern_without_delimiter'] = ObjectSerializer::toFormValue($pattern_without_delimiter); + } + // form params + if ($byte !== null) { + $formParams['byte'] = ObjectSerializer::toFormValue($byte); + } + // form params + if ($binary !== null) { + $multipart = true; + $formParams['binary'] = \GuzzleHttp\Psr7\try_fopen(ObjectSerializer::toFormValue($binary), 'rb'); + } + // form params + if ($date !== null) { + $formParams['date'] = ObjectSerializer::toFormValue($date); + } + // form params + if ($date_time !== null) { + $formParams['dateTime'] = ObjectSerializer::toFormValue($date_time); + } + // form params + if ($password !== null) { + $formParams['password'] = ObjectSerializer::toFormValue($password); + } + // form params + if ($callback !== null) { + $formParams['callback'] = ObjectSerializer::toFormValue($callback); + } + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + ['application/x-www-form-urlencoded'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + // this endpoint requires HTTP basic authentication + if ($this->config->getUsername() !== null || $this->config->getPassword() !== null) { + $headers['Authorization'] = 'Basic ' . base64_encode($this->config->getUsername() . ":" . $this->config->getPassword()); + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation testEnumParameters + * + * To test enum parameters + * + * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) + * @param string $enum_header_string Header parameter enum test (string) (optional) + * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) + * @param string $enum_query_string Query parameter enum test (string) (optional) + * @param int $enum_query_integer Query parameter enum test (double) (optional) + * @param double $enum_query_double Query parameter enum test (double) (optional) + * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional) + * @param string $enum_form_string Form parameter enum test (string) (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function testEnumParameters($enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null, $enum_form_string_array = null, $enum_form_string = null) + { + $this->testEnumParametersWithHttpInfo($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_form_string_array, $enum_form_string); + } + + /** + * Operation testEnumParametersWithHttpInfo + * + * To test enum parameters + * + * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) + * @param string $enum_header_string Header parameter enum test (string) (optional) + * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) + * @param string $enum_query_string Query parameter enum test (string) (optional) + * @param int $enum_query_integer Query parameter enum test (double) (optional) + * @param double $enum_query_double Query parameter enum test (double) (optional) + * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional) + * @param string $enum_form_string Form parameter enum test (string) (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function testEnumParametersWithHttpInfo($enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null, $enum_form_string_array = null, $enum_form_string = null) + { + $returnType = ''; + $request = $this->testEnumParametersRequest($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_form_string_array, $enum_form_string); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation testEnumParametersAsync + * + * To test enum parameters + * + * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) + * @param string $enum_header_string Header parameter enum test (string) (optional) + * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) + * @param string $enum_query_string Query parameter enum test (string) (optional) + * @param int $enum_query_integer Query parameter enum test (double) (optional) + * @param double $enum_query_double Query parameter enum test (double) (optional) + * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional) + * @param string $enum_form_string Form parameter enum test (string) (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testEnumParametersAsync($enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null, $enum_form_string_array = null, $enum_form_string = null) + { + return $this->testEnumParametersAsyncWithHttpInfo($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_form_string_array, $enum_form_string) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testEnumParametersAsyncWithHttpInfo + * + * To test enum parameters + * + * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) + * @param string $enum_header_string Header parameter enum test (string) (optional) + * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) + * @param string $enum_query_string Query parameter enum test (string) (optional) + * @param int $enum_query_integer Query parameter enum test (double) (optional) + * @param double $enum_query_double Query parameter enum test (double) (optional) + * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional) + * @param string $enum_form_string Form parameter enum test (string) (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testEnumParametersAsyncWithHttpInfo($enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null, $enum_form_string_array = null, $enum_form_string = null) + { + $returnType = ''; + $request = $this->testEnumParametersRequest($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_form_string_array, $enum_form_string); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testEnumParameters' + * + * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) + * @param string $enum_header_string Header parameter enum test (string) (optional) + * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) + * @param string $enum_query_string Query parameter enum test (string) (optional) + * @param int $enum_query_integer Query parameter enum test (double) (optional) + * @param double $enum_query_double Query parameter enum test (double) (optional) + * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional) + * @param string $enum_form_string Form parameter enum test (string) (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function testEnumParametersRequest($enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null, $enum_form_string_array = null, $enum_form_string = null) + { + + $resourcePath = '/fake'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + if (is_array($enum_query_string_array)) { + $enum_query_string_array = ObjectSerializer::serializeCollection($enum_query_string_array, 'multi', true); + } + if ($enum_query_string_array !== null) { + $queryParams['enum_query_string_array'] = ObjectSerializer::toQueryValue($enum_query_string_array); + } + // query params + if ($enum_query_string !== null) { + $queryParams['enum_query_string'] = ObjectSerializer::toQueryValue($enum_query_string); + } + // query params + if ($enum_query_integer !== null) { + $queryParams['enum_query_integer'] = ObjectSerializer::toQueryValue($enum_query_integer); + } + // query params + if ($enum_query_double !== null) { + $queryParams['enum_query_double'] = ObjectSerializer::toQueryValue($enum_query_double); + } + // header params + if (is_array($enum_header_string_array)) { + $enum_header_string_array = ObjectSerializer::serializeCollection($enum_header_string_array, 'csv'); + } + if ($enum_header_string_array !== null) { + $headerParams['enum_header_string_array'] = ObjectSerializer::toHeaderValue($enum_header_string_array); + } + // header params + if ($enum_header_string !== null) { + $headerParams['enum_header_string'] = ObjectSerializer::toHeaderValue($enum_header_string); + } + + + // form params + if ($enum_form_string_array !== null) { + $formParams['enum_form_string_array'] = ObjectSerializer::toFormValue($enum_form_string_array); + } + // form params + if ($enum_form_string !== null) { + $formParams['enum_form_string'] = ObjectSerializer::toFormValue($enum_form_string); + } + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + ['application/x-www-form-urlencoded'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation testInlineAdditionalProperties + * + * test inline additionalProperties + * + * @param map[string,string] $unknown_base_type request body (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function testInlineAdditionalProperties($unknown_base_type) + { + $this->testInlineAdditionalPropertiesWithHttpInfo($unknown_base_type); + } + + /** + * Operation testInlineAdditionalPropertiesWithHttpInfo + * + * test inline additionalProperties + * + * @param map[string,string] $unknown_base_type request body (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function testInlineAdditionalPropertiesWithHttpInfo($unknown_base_type) + { + $returnType = ''; + $request = $this->testInlineAdditionalPropertiesRequest($unknown_base_type); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation testInlineAdditionalPropertiesAsync + * + * test inline additionalProperties + * + * @param map[string,string] $unknown_base_type request body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testInlineAdditionalPropertiesAsync($unknown_base_type) + { + return $this->testInlineAdditionalPropertiesAsyncWithHttpInfo($unknown_base_type) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testInlineAdditionalPropertiesAsyncWithHttpInfo + * + * test inline additionalProperties + * + * @param map[string,string] $unknown_base_type request body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testInlineAdditionalPropertiesAsyncWithHttpInfo($unknown_base_type) + { + $returnType = ''; + $request = $this->testInlineAdditionalPropertiesRequest($unknown_base_type); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testInlineAdditionalProperties' + * + * @param map[string,string] $unknown_base_type request body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function testInlineAdditionalPropertiesRequest($unknown_base_type) + { + // verify the required parameter 'unknown_base_type' is set + if ($unknown_base_type === null || (is_array($unknown_base_type) && count($unknown_base_type) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $unknown_base_type when calling testInlineAdditionalProperties' + ); + } + + $resourcePath = '/fake/inline-additionalProperties'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($unknown_base_type)) { + $_tempBody = $unknown_base_type; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation testJsonFormData + * + * test json serialization of form data + * + * @param Body4 $body4 body4 (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function testJsonFormData($body4 = null) + { + $this->testJsonFormDataWithHttpInfo($body4); + } + + /** + * Operation testJsonFormDataWithHttpInfo + * + * test json serialization of form data + * + * @param Body4 $body4 (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function testJsonFormDataWithHttpInfo($body4 = null) + { + $returnType = ''; + $request = $this->testJsonFormDataRequest($body4); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation testJsonFormDataAsync + * + * test json serialization of form data + * + * @param Body4 $body4 (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testJsonFormDataAsync($body4 = null) + { + return $this->testJsonFormDataAsyncWithHttpInfo($body4) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testJsonFormDataAsyncWithHttpInfo + * + * test json serialization of form data + * + * @param Body4 $body4 (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testJsonFormDataAsyncWithHttpInfo($body4 = null) + { + $returnType = ''; + $request = $this->testJsonFormDataRequest($body4); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testJsonFormData' + * + * @param Body4 $body4 (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function testJsonFormDataRequest($body4 = null) + { + + $resourcePath = '/fake/jsonFormData'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($body4)) { + $_tempBody = $body4; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/FakeClassnameTags123Api.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/FakeClassnameTags123Api.php new file mode 100644 index 000000000000..d41810b64b90 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/FakeClassnameTags123Api.php @@ -0,0 +1,370 @@ +client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation testClassname + * + * To test class name in snake case + * + * @param Client $client client model (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\Client + */ + public function testClassname($client) + { + list($response) = $this->testClassnameWithHttpInfo($client); + return $response; + } + + /** + * Operation testClassnameWithHttpInfo + * + * To test class name in snake case + * + * @param Client $client client model (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) + */ + public function testClassnameWithHttpInfo($client) + { + $returnType = '\Swagger\Client\Model\Client'; + $request = $this->testClassnameRequest($client); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\Client', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation testClassnameAsync + * + * To test class name in snake case + * + * @param Client $client client model (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testClassnameAsync($client) + { + return $this->testClassnameAsyncWithHttpInfo($client) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testClassnameAsyncWithHttpInfo + * + * To test class name in snake case + * + * @param Client $client client model (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testClassnameAsyncWithHttpInfo($client) + { + $returnType = '\Swagger\Client\Model\Client'; + $request = $this->testClassnameRequest($client); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testClassname' + * + * @param Client $client client model (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function testClassnameRequest($client) + { + // verify the required parameter 'client' is set + if ($client === null || (is_array($client) && count($client) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $client when calling testClassname' + ); + } + + $resourcePath = '/fake_classname_test'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($client)) { + $_tempBody = $client; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key_query'); + if ($apiKey !== null) { + $queryParams['api_key_query'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'PATCH', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php new file mode 100644 index 000000000000..87f393b21222 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -0,0 +1,2123 @@ +client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation addPet + * + * Add a new pet to the store + * + * @param Pet $pet Pet object that needs to be added to the store (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function addPet($pet) + { + $this->addPetWithHttpInfo($pet); + } + + /** + * Operation addPetWithHttpInfo + * + * Add a new pet to the store + * + * @param Pet $pet Pet object that needs to be added to the store (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function addPetWithHttpInfo($pet) + { + $returnType = ''; + $request = $this->addPetRequest($pet); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation addPetAsync + * + * Add a new pet to the store + * + * @param Pet $pet Pet object that needs to be added to the store (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function addPetAsync($pet) + { + return $this->addPetAsyncWithHttpInfo($pet) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation addPetAsyncWithHttpInfo + * + * Add a new pet to the store + * + * @param Pet $pet Pet object that needs to be added to the store (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function addPetAsyncWithHttpInfo($pet) + { + $returnType = ''; + $request = $this->addPetRequest($pet); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'addPet' + * + * @param Pet $pet Pet object that needs to be added to the store (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function addPetRequest($pet) + { + // verify the required parameter 'pet' is set + if ($pet === null || (is_array($pet) && count($pet) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $pet when calling addPet' + ); + } + + $resourcePath = '/pet'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($pet)) { + $_tempBody = $pet; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation deletePet + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string $api_key api_key (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function deletePet($pet_id, $api_key = null) + { + $this->deletePetWithHttpInfo($pet_id, $api_key); + } + + /** + * Operation deletePetWithHttpInfo + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string $api_key (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function deletePetWithHttpInfo($pet_id, $api_key = null) + { + $returnType = ''; + $request = $this->deletePetRequest($pet_id, $api_key); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation deletePetAsync + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string $api_key (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deletePetAsync($pet_id, $api_key = null) + { + return $this->deletePetAsyncWithHttpInfo($pet_id, $api_key) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation deletePetAsyncWithHttpInfo + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string $api_key (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deletePetAsyncWithHttpInfo($pet_id, $api_key = null) + { + $returnType = ''; + $request = $this->deletePetRequest($pet_id, $api_key); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'deletePet' + * + * @param int $pet_id Pet id to delete (required) + * @param string $api_key (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function deletePetRequest($pet_id, $api_key = null) + { + // verify the required parameter 'pet_id' is set + if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $pet_id when calling deletePet' + ); + } + + $resourcePath = '/pet/{petId}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // header params + if ($api_key !== null) { + $headerParams['api_key'] = ObjectSerializer::toHeaderValue($api_key); + } + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + '{' . 'petId' . '}', + ObjectSerializer::toPathValue($pet_id), + $resourcePath + ); + } + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'DELETE', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation findPetsByStatus + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\Pet[] + */ + public function findPetsByStatus($status) + { + list($response) = $this->findPetsByStatusWithHttpInfo($status); + return $response; + } + + /** + * Operation findPetsByStatusWithHttpInfo + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) + */ + public function findPetsByStatusWithHttpInfo($status) + { + $returnType = '\Swagger\Client\Model\Pet[]'; + $request = $this->findPetsByStatusRequest($status); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\Pet[]', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation findPetsByStatusAsync + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function findPetsByStatusAsync($status) + { + return $this->findPetsByStatusAsyncWithHttpInfo($status) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation findPetsByStatusAsyncWithHttpInfo + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function findPetsByStatusAsyncWithHttpInfo($status) + { + $returnType = '\Swagger\Client\Model\Pet[]'; + $request = $this->findPetsByStatusRequest($status); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'findPetsByStatus' + * + * @param string[] $status Status values that need to be considered for filter (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function findPetsByStatusRequest($status) + { + // verify the required parameter 'status' is set + if ($status === null || (is_array($status) && count($status) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $status when calling findPetsByStatus' + ); + } + + $resourcePath = '/pet/findByStatus'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + if (is_array($status)) { + $status = ObjectSerializer::serializeCollection($status, 'multi', true); + } + if ($status !== null) { + $queryParams['status'] = ObjectSerializer::toQueryValue($status); + } + + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation findPetsByTags + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\Pet[] + */ + public function findPetsByTags($tags) + { + list($response) = $this->findPetsByTagsWithHttpInfo($tags); + return $response; + } + + /** + * Operation findPetsByTagsWithHttpInfo + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) + */ + public function findPetsByTagsWithHttpInfo($tags) + { + $returnType = '\Swagger\Client\Model\Pet[]'; + $request = $this->findPetsByTagsRequest($tags); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\Pet[]', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation findPetsByTagsAsync + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function findPetsByTagsAsync($tags) + { + return $this->findPetsByTagsAsyncWithHttpInfo($tags) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation findPetsByTagsAsyncWithHttpInfo + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function findPetsByTagsAsyncWithHttpInfo($tags) + { + $returnType = '\Swagger\Client\Model\Pet[]'; + $request = $this->findPetsByTagsRequest($tags); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'findPetsByTags' + * + * @param string[] $tags Tags to filter by (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function findPetsByTagsRequest($tags) + { + // verify the required parameter 'tags' is set + if ($tags === null || (is_array($tags) && count($tags) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $tags when calling findPetsByTags' + ); + } + + $resourcePath = '/pet/findByTags'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + if (is_array($tags)) { + $tags = ObjectSerializer::serializeCollection($tags, 'multi', true); + } + if ($tags !== null) { + $queryParams['tags'] = ObjectSerializer::toQueryValue($tags); + } + + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation getPetById + * + * Find pet by ID + * + * @param int $pet_id ID of pet to return (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\Pet + */ + public function getPetById($pet_id) + { + list($response) = $this->getPetByIdWithHttpInfo($pet_id); + return $response; + } + + /** + * Operation getPetByIdWithHttpInfo + * + * Find pet by ID + * + * @param int $pet_id ID of pet to return (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) + */ + public function getPetByIdWithHttpInfo($pet_id) + { + $returnType = '\Swagger\Client\Model\Pet'; + $request = $this->getPetByIdRequest($pet_id); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\Pet', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation getPetByIdAsync + * + * Find pet by ID + * + * @param int $pet_id ID of pet to return (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPetByIdAsync($pet_id) + { + return $this->getPetByIdAsyncWithHttpInfo($pet_id) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getPetByIdAsyncWithHttpInfo + * + * Find pet by ID + * + * @param int $pet_id ID of pet to return (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPetByIdAsyncWithHttpInfo($pet_id) + { + $returnType = '\Swagger\Client\Model\Pet'; + $request = $this->getPetByIdRequest($pet_id); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getPetById' + * + * @param int $pet_id ID of pet to return (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function getPetByIdRequest($pet_id) + { + // verify the required parameter 'pet_id' is set + if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $pet_id when calling getPetById' + ); + } + + $resourcePath = '/pet/{petId}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + '{' . 'petId' . '}', + ObjectSerializer::toPathValue($pet_id), + $resourcePath + ); + } + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $headers['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation updatePet + * + * Update an existing pet + * + * @param Pet $pet Pet object that needs to be added to the store (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function updatePet($pet) + { + $this->updatePetWithHttpInfo($pet); + } + + /** + * Operation updatePetWithHttpInfo + * + * Update an existing pet + * + * @param Pet $pet Pet object that needs to be added to the store (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function updatePetWithHttpInfo($pet) + { + $returnType = ''; + $request = $this->updatePetRequest($pet); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation updatePetAsync + * + * Update an existing pet + * + * @param Pet $pet Pet object that needs to be added to the store (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updatePetAsync($pet) + { + return $this->updatePetAsyncWithHttpInfo($pet) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation updatePetAsyncWithHttpInfo + * + * Update an existing pet + * + * @param Pet $pet Pet object that needs to be added to the store (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updatePetAsyncWithHttpInfo($pet) + { + $returnType = ''; + $request = $this->updatePetRequest($pet); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'updatePet' + * + * @param Pet $pet Pet object that needs to be added to the store (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function updatePetRequest($pet) + { + // verify the required parameter 'pet' is set + if ($pet === null || (is_array($pet) && count($pet) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $pet when calling updatePet' + ); + } + + $resourcePath = '/pet'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($pet)) { + $_tempBody = $pet; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'PUT', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation updatePetWithForm + * + * Updates a pet in the store with form data + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string $name Updated name of the pet (optional) + * @param string $status Updated status of the pet (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function updatePetWithForm($pet_id, $name = null, $status = null) + { + $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status); + } + + /** + * Operation updatePetWithFormWithHttpInfo + * + * Updates a pet in the store with form data + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string $name Updated name of the pet (optional) + * @param string $status Updated status of the pet (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null) + { + $returnType = ''; + $request = $this->updatePetWithFormRequest($pet_id, $name, $status); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation updatePetWithFormAsync + * + * Updates a pet in the store with form data + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string $name Updated name of the pet (optional) + * @param string $status Updated status of the pet (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updatePetWithFormAsync($pet_id, $name = null, $status = null) + { + return $this->updatePetWithFormAsyncWithHttpInfo($pet_id, $name, $status) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation updatePetWithFormAsyncWithHttpInfo + * + * Updates a pet in the store with form data + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string $name Updated name of the pet (optional) + * @param string $status Updated status of the pet (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updatePetWithFormAsyncWithHttpInfo($pet_id, $name = null, $status = null) + { + $returnType = ''; + $request = $this->updatePetWithFormRequest($pet_id, $name, $status); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'updatePetWithForm' + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string $name Updated name of the pet (optional) + * @param string $status Updated status of the pet (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function updatePetWithFormRequest($pet_id, $name = null, $status = null) + { + // verify the required parameter 'pet_id' is set + if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $pet_id when calling updatePetWithForm' + ); + } + + $resourcePath = '/pet/{petId}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + '{' . 'petId' . '}', + ObjectSerializer::toPathValue($pet_id), + $resourcePath + ); + } + + // form params + if ($name !== null) { + $formParams['name'] = ObjectSerializer::toFormValue($name); + } + // form params + if ($status !== null) { + $formParams['status'] = ObjectSerializer::toFormValue($status); + } + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + ['application/x-www-form-urlencoded'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation uploadFile + * + * uploads an image + * + * @param int $pet_id ID of pet to update (required) + * @param string $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject $file file to upload (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\ApiResponse + */ + public function uploadFile($pet_id, $additional_metadata = null, $file = null) + { + list($response) = $this->uploadFileWithHttpInfo($pet_id, $additional_metadata, $file); + return $response; + } + + /** + * Operation uploadFileWithHttpInfo + * + * uploads an image + * + * @param int $pet_id ID of pet to update (required) + * @param string $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject $file file to upload (optional) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) + */ + public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null) + { + $returnType = '\Swagger\Client\Model\ApiResponse'; + $request = $this->uploadFileRequest($pet_id, $additional_metadata, $file); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\ApiResponse', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation uploadFileAsync + * + * uploads an image + * + * @param int $pet_id ID of pet to update (required) + * @param string $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject $file file to upload (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function uploadFileAsync($pet_id, $additional_metadata = null, $file = null) + { + return $this->uploadFileAsyncWithHttpInfo($pet_id, $additional_metadata, $file) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation uploadFileAsyncWithHttpInfo + * + * uploads an image + * + * @param int $pet_id ID of pet to update (required) + * @param string $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject $file file to upload (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function uploadFileAsyncWithHttpInfo($pet_id, $additional_metadata = null, $file = null) + { + $returnType = '\Swagger\Client\Model\ApiResponse'; + $request = $this->uploadFileRequest($pet_id, $additional_metadata, $file); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'uploadFile' + * + * @param int $pet_id ID of pet to update (required) + * @param string $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject $file file to upload (optional) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function uploadFileRequest($pet_id, $additional_metadata = null, $file = null) + { + // verify the required parameter 'pet_id' is set + if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $pet_id when calling uploadFile' + ); + } + + $resourcePath = '/pet/{petId}/uploadImage'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + '{' . 'petId' . '}', + ObjectSerializer::toPathValue($pet_id), + $resourcePath + ); + } + + // form params + if ($additional_metadata !== null) { + $formParams['additionalMetadata'] = ObjectSerializer::toFormValue($additional_metadata); + } + // form params + if ($file !== null) { + $multipart = true; + $formParams['file'] = \GuzzleHttp\Psr7\try_fopen(ObjectSerializer::toFormValue($file), 'rb'); + } + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['multipart/form-data'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php new file mode 100644 index 000000000000..1cdc67aba3d3 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -0,0 +1,1107 @@ +client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation deleteOrder + * + * Delete purchase order by ID + * + * @param string $order_id ID of the order that needs to be deleted (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function deleteOrder($order_id) + { + $this->deleteOrderWithHttpInfo($order_id); + } + + /** + * Operation deleteOrderWithHttpInfo + * + * Delete purchase order by ID + * + * @param string $order_id ID of the order that needs to be deleted (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function deleteOrderWithHttpInfo($order_id) + { + $returnType = ''; + $request = $this->deleteOrderRequest($order_id); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation deleteOrderAsync + * + * Delete purchase order by ID + * + * @param string $order_id ID of the order that needs to be deleted (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deleteOrderAsync($order_id) + { + return $this->deleteOrderAsyncWithHttpInfo($order_id) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation deleteOrderAsyncWithHttpInfo + * + * Delete purchase order by ID + * + * @param string $order_id ID of the order that needs to be deleted (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deleteOrderAsyncWithHttpInfo($order_id) + { + $returnType = ''; + $request = $this->deleteOrderRequest($order_id); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'deleteOrder' + * + * @param string $order_id ID of the order that needs to be deleted (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function deleteOrderRequest($order_id) + { + // verify the required parameter 'order_id' is set + if ($order_id === null || (is_array($order_id) && count($order_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $order_id when calling deleteOrder' + ); + } + + $resourcePath = '/store/order/{order_id}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + // path params + if ($order_id !== null) { + $resourcePath = str_replace( + '{' . 'order_id' . '}', + ObjectSerializer::toPathValue($order_id), + $resourcePath + ); + } + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'DELETE', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation getInventory + * + * Returns pet inventories by status + * + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return map[string,int] + */ + public function getInventory() + { + list($response) = $this->getInventoryWithHttpInfo(); + return $response; + } + + /** + * Operation getInventoryWithHttpInfo + * + * Returns pet inventories by status + * + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of map[string,int], HTTP status code, HTTP response headers (array of strings) + */ + public function getInventoryWithHttpInfo() + { + $returnType = 'map[string,int]'; + $request = $this->getInventoryRequest(); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + 'map[string,int]', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation getInventoryAsync + * + * Returns pet inventories by status + * + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getInventoryAsync() + { + return $this->getInventoryAsyncWithHttpInfo() + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getInventoryAsyncWithHttpInfo + * + * Returns pet inventories by status + * + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getInventoryAsyncWithHttpInfo() + { + $returnType = 'map[string,int]'; + $request = $this->getInventoryRequest(); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getInventory' + * + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function getInventoryRequest() + { + + $resourcePath = '/store/inventory'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $headers['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation getOrderById + * + * Find purchase order by ID + * + * @param int $order_id ID of pet that needs to be fetched (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\Order + */ + public function getOrderById($order_id) + { + list($response) = $this->getOrderByIdWithHttpInfo($order_id); + return $response; + } + + /** + * Operation getOrderByIdWithHttpInfo + * + * Find purchase order by ID + * + * @param int $order_id ID of pet that needs to be fetched (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) + */ + public function getOrderByIdWithHttpInfo($order_id) + { + $returnType = '\Swagger\Client\Model\Order'; + $request = $this->getOrderByIdRequest($order_id); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\Order', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation getOrderByIdAsync + * + * Find purchase order by ID + * + * @param int $order_id ID of pet that needs to be fetched (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getOrderByIdAsync($order_id) + { + return $this->getOrderByIdAsyncWithHttpInfo($order_id) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getOrderByIdAsyncWithHttpInfo + * + * Find purchase order by ID + * + * @param int $order_id ID of pet that needs to be fetched (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getOrderByIdAsyncWithHttpInfo($order_id) + { + $returnType = '\Swagger\Client\Model\Order'; + $request = $this->getOrderByIdRequest($order_id); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getOrderById' + * + * @param int $order_id ID of pet that needs to be fetched (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function getOrderByIdRequest($order_id) + { + // verify the required parameter 'order_id' is set + if ($order_id === null || (is_array($order_id) && count($order_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $order_id when calling getOrderById' + ); + } + if ($order_id > 5) { + throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be smaller than or equal to 5.'); + } + if ($order_id < 1) { + throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be bigger than or equal to 1.'); + } + + + $resourcePath = '/store/order/{order_id}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + // path params + if ($order_id !== null) { + $resourcePath = str_replace( + '{' . 'order_id' . '}', + ObjectSerializer::toPathValue($order_id), + $resourcePath + ); + } + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation placeOrder + * + * Place an order for a pet + * + * @param Order $order order placed for purchasing the pet (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\Order + */ + public function placeOrder($order) + { + list($response) = $this->placeOrderWithHttpInfo($order); + return $response; + } + + /** + * Operation placeOrderWithHttpInfo + * + * Place an order for a pet + * + * @param Order $order order placed for purchasing the pet (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) + */ + public function placeOrderWithHttpInfo($order) + { + $returnType = '\Swagger\Client\Model\Order'; + $request = $this->placeOrderRequest($order); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\Order', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation placeOrderAsync + * + * Place an order for a pet + * + * @param Order $order order placed for purchasing the pet (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function placeOrderAsync($order) + { + return $this->placeOrderAsyncWithHttpInfo($order) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation placeOrderAsyncWithHttpInfo + * + * Place an order for a pet + * + * @param Order $order order placed for purchasing the pet (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function placeOrderAsyncWithHttpInfo($order) + { + $returnType = '\Swagger\Client\Model\Order'; + $request = $this->placeOrderRequest($order); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'placeOrder' + * + * @param Order $order order placed for purchasing the pet (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function placeOrderRequest($order) + { + // verify the required parameter 'order' is set + if ($order === null || (is_array($order) && count($order) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $order when calling placeOrder' + ); + } + + $resourcePath = '/store/order'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($order)) { + $_tempBody = $order; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php new file mode 100644 index 000000000000..db186a5357d8 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -0,0 +1,1973 @@ +client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation createUser + * + * Create user + * + * @param User $user Created user object (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function createUser($user) + { + $this->createUserWithHttpInfo($user); + } + + /** + * Operation createUserWithHttpInfo + * + * Create user + * + * @param User $user Created user object (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function createUserWithHttpInfo($user) + { + $returnType = ''; + $request = $this->createUserRequest($user); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation createUserAsync + * + * Create user + * + * @param User $user Created user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUserAsync($user) + { + return $this->createUserAsyncWithHttpInfo($user) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation createUserAsyncWithHttpInfo + * + * Create user + * + * @param User $user Created user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUserAsyncWithHttpInfo($user) + { + $returnType = ''; + $request = $this->createUserRequest($user); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'createUser' + * + * @param User $user Created user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function createUserRequest($user) + { + // verify the required parameter 'user' is set + if ($user === null || (is_array($user) && count($user) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $user when calling createUser' + ); + } + + $resourcePath = '/user'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($user)) { + $_tempBody = $user; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation createUsersWithArrayInput + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $user List of user object (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function createUsersWithArrayInput($user) + { + $this->createUsersWithArrayInputWithHttpInfo($user); + } + + /** + * Operation createUsersWithArrayInputWithHttpInfo + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $user List of user object (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function createUsersWithArrayInputWithHttpInfo($user) + { + $returnType = ''; + $request = $this->createUsersWithArrayInputRequest($user); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation createUsersWithArrayInputAsync + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $user List of user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUsersWithArrayInputAsync($user) + { + return $this->createUsersWithArrayInputAsyncWithHttpInfo($user) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation createUsersWithArrayInputAsyncWithHttpInfo + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $user List of user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUsersWithArrayInputAsyncWithHttpInfo($user) + { + $returnType = ''; + $request = $this->createUsersWithArrayInputRequest($user); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'createUsersWithArrayInput' + * + * @param \Swagger\Client\Model\User[] $user List of user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function createUsersWithArrayInputRequest($user) + { + // verify the required parameter 'user' is set + if ($user === null || (is_array($user) && count($user) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $user when calling createUsersWithArrayInput' + ); + } + + $resourcePath = '/user/createWithArray'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($user)) { + $_tempBody = $user; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation createUsersWithListInput + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $user List of user object (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function createUsersWithListInput($user) + { + $this->createUsersWithListInputWithHttpInfo($user); + } + + /** + * Operation createUsersWithListInputWithHttpInfo + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $user List of user object (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function createUsersWithListInputWithHttpInfo($user) + { + $returnType = ''; + $request = $this->createUsersWithListInputRequest($user); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation createUsersWithListInputAsync + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $user List of user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUsersWithListInputAsync($user) + { + return $this->createUsersWithListInputAsyncWithHttpInfo($user) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation createUsersWithListInputAsyncWithHttpInfo + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $user List of user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUsersWithListInputAsyncWithHttpInfo($user) + { + $returnType = ''; + $request = $this->createUsersWithListInputRequest($user); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'createUsersWithListInput' + * + * @param \Swagger\Client\Model\User[] $user List of user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function createUsersWithListInputRequest($user) + { + // verify the required parameter 'user' is set + if ($user === null || (is_array($user) && count($user) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $user when calling createUsersWithListInput' + ); + } + + $resourcePath = '/user/createWithList'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($user)) { + $_tempBody = $user; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation deleteUser + * + * Delete user + * + * @param string $username The name that needs to be deleted (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function deleteUser($username) + { + $this->deleteUserWithHttpInfo($username); + } + + /** + * Operation deleteUserWithHttpInfo + * + * Delete user + * + * @param string $username The name that needs to be deleted (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function deleteUserWithHttpInfo($username) + { + $returnType = ''; + $request = $this->deleteUserRequest($username); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation deleteUserAsync + * + * Delete user + * + * @param string $username The name that needs to be deleted (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deleteUserAsync($username) + { + return $this->deleteUserAsyncWithHttpInfo($username) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation deleteUserAsyncWithHttpInfo + * + * Delete user + * + * @param string $username The name that needs to be deleted (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deleteUserAsyncWithHttpInfo($username) + { + $returnType = ''; + $request = $this->deleteUserRequest($username); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'deleteUser' + * + * @param string $username The name that needs to be deleted (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function deleteUserRequest($username) + { + // verify the required parameter 'username' is set + if ($username === null || (is_array($username) && count($username) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $username when calling deleteUser' + ); + } + + $resourcePath = '/user/{username}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + // path params + if ($username !== null) { + $resourcePath = str_replace( + '{' . 'username' . '}', + ObjectSerializer::toPathValue($username), + $resourcePath + ); + } + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'DELETE', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation getUserByName + * + * Get user by user name + * + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\User + */ + public function getUserByName($username) + { + list($response) = $this->getUserByNameWithHttpInfo($username); + return $response; + } + + /** + * Operation getUserByNameWithHttpInfo + * + * Get user by user name + * + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\User, HTTP status code, HTTP response headers (array of strings) + */ + public function getUserByNameWithHttpInfo($username) + { + $returnType = '\Swagger\Client\Model\User'; + $request = $this->getUserByNameRequest($username); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\User', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation getUserByNameAsync + * + * Get user by user name + * + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getUserByNameAsync($username) + { + return $this->getUserByNameAsyncWithHttpInfo($username) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getUserByNameAsyncWithHttpInfo + * + * Get user by user name + * + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getUserByNameAsyncWithHttpInfo($username) + { + $returnType = '\Swagger\Client\Model\User'; + $request = $this->getUserByNameRequest($username); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getUserByName' + * + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function getUserByNameRequest($username) + { + // verify the required parameter 'username' is set + if ($username === null || (is_array($username) && count($username) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $username when calling getUserByName' + ); + } + + $resourcePath = '/user/{username}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + // path params + if ($username !== null) { + $resourcePath = str_replace( + '{' . 'username' . '}', + ObjectSerializer::toPathValue($username), + $resourcePath + ); + } + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation loginUser + * + * Logs user into the system + * + * @param string $username The user name for login (required) + * @param string $password The password for login in clear text (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return string + */ + public function loginUser($username, $password) + { + list($response) = $this->loginUserWithHttpInfo($username, $password); + return $response; + } + + /** + * Operation loginUserWithHttpInfo + * + * Logs user into the system + * + * @param string $username The user name for login (required) + * @param string $password The password for login in clear text (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of string, HTTP status code, HTTP response headers (array of strings) + */ + public function loginUserWithHttpInfo($username, $password) + { + $returnType = 'string'; + $request = $this->loginUserRequest($username, $password); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + 'string', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation loginUserAsync + * + * Logs user into the system + * + * @param string $username The user name for login (required) + * @param string $password The password for login in clear text (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function loginUserAsync($username, $password) + { + return $this->loginUserAsyncWithHttpInfo($username, $password) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation loginUserAsyncWithHttpInfo + * + * Logs user into the system + * + * @param string $username The user name for login (required) + * @param string $password The password for login in clear text (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function loginUserAsyncWithHttpInfo($username, $password) + { + $returnType = 'string'; + $request = $this->loginUserRequest($username, $password); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'loginUser' + * + * @param string $username The user name for login (required) + * @param string $password The password for login in clear text (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function loginUserRequest($username, $password) + { + // verify the required parameter 'username' is set + if ($username === null || (is_array($username) && count($username) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $username when calling loginUser' + ); + } + // verify the required parameter 'password' is set + if ($password === null || (is_array($password) && count($password) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $password when calling loginUser' + ); + } + + $resourcePath = '/user/login'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + if ($username !== null) { + $queryParams['username'] = ObjectSerializer::toQueryValue($username); + } + // query params + if ($password !== null) { + $queryParams['password'] = ObjectSerializer::toQueryValue($password); + } + + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation logoutUser + * + * Logs out current logged in user session + * + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function logoutUser() + { + $this->logoutUserWithHttpInfo(); + } + + /** + * Operation logoutUserWithHttpInfo + * + * Logs out current logged in user session + * + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function logoutUserWithHttpInfo() + { + $returnType = ''; + $request = $this->logoutUserRequest(); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation logoutUserAsync + * + * Logs out current logged in user session + * + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function logoutUserAsync() + { + return $this->logoutUserAsyncWithHttpInfo() + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation logoutUserAsyncWithHttpInfo + * + * Logs out current logged in user session + * + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function logoutUserAsyncWithHttpInfo() + { + $returnType = ''; + $request = $this->logoutUserRequest(); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'logoutUser' + * + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function logoutUserRequest() + { + + $resourcePath = '/user/logout'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + [] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation updateUser + * + * Updated user + * + * @param string $username name that need to be deleted (required) + * @param User $user Updated user object (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function updateUser($username, $user) + { + $this->updateUserWithHttpInfo($username, $user); + } + + /** + * Operation updateUserWithHttpInfo + * + * Updated user + * + * @param string $username name that need to be deleted (required) + * @param User $user Updated user object (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function updateUserWithHttpInfo($username, $user) + { + $returnType = ''; + $request = $this->updateUserRequest($username, $user); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation updateUserAsync + * + * Updated user + * + * @param string $username name that need to be deleted (required) + * @param User $user Updated user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updateUserAsync($username, $user) + { + return $this->updateUserAsyncWithHttpInfo($username, $user) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation updateUserAsyncWithHttpInfo + * + * Updated user + * + * @param string $username name that need to be deleted (required) + * @param User $user Updated user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updateUserAsyncWithHttpInfo($username, $user) + { + $returnType = ''; + $request = $this->updateUserRequest($username, $user); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'updateUser' + * + * @param string $username name that need to be deleted (required) + * @param User $user Updated user object (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function updateUserRequest($username, $user) + { + // verify the required parameter 'username' is set + if ($username === null || (is_array($username) && count($username) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $username when calling updateUser' + ); + } + // verify the required parameter 'user' is set + if ($user === null || (is_array($user) && count($user) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $user when calling updateUser' + ); + } + + $resourcePath = '/user/{username}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + // path params + if ($username !== null) { + $resourcePath = str_replace( + '{' . 'username' . '}', + ObjectSerializer::toPathValue($username), + $resourcePath + ); + } + + // body params + $_tempBody = null; + if (isset($user)) { + $_tempBody = $user; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'PUT', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/ApiException.php new file mode 100644 index 000000000000..b0825e46f6b6 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -0,0 +1,121 @@ +responseHeaders = $responseHeaders; + $this->responseBody = $responseBody; + } + + /** + * Gets the HTTP response header + * + * @return string[]|null HTTP response header + */ + public function getResponseHeaders() + { + return $this->responseHeaders; + } + + /** + * Gets the HTTP body of the server response either as Json or string + * + * @return mixed HTTP body of the server response either as \stdClass or string + */ + public function getResponseBody() + { + return $this->responseBody; + } + + /** + * Sets the deseralized response object (during deserialization) + * + * @param mixed $obj Deserialized response object + * + * @return void + */ + public function setResponseObject($obj) + { + $this->responseObject = $obj; + } + + /** + * Gets the deseralized response object (during deserialization) + * + * @return mixed the deserialized response object + */ + public function getResponseObject() + { + return $this->responseObject; + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Configuration.php new file mode 100644 index 000000000000..2ce3e63b8a95 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -0,0 +1,429 @@ +tempFolderPath = sys_get_temp_dir(); + } + + /** + * Sets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $key API key or token + * + * @return $this + */ + public function setApiKey($apiKeyIdentifier, $key) + { + $this->apiKeys[$apiKeyIdentifier] = $key; + return $this; + } + + /** + * Gets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string API key or token + */ + public function getApiKey($apiKeyIdentifier) + { + return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; + } + + /** + * Sets the prefix for API key (e.g. Bearer) + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $prefix API key prefix, e.g. Bearer + * + * @return $this + */ + public function setApiKeyPrefix($apiKeyIdentifier, $prefix) + { + $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; + return $this; + } + + /** + * Gets API key prefix + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string + */ + public function getApiKeyPrefix($apiKeyIdentifier) + { + return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; + } + + /** + * Sets the access token for OAuth + * + * @param string $accessToken Token for OAuth + * + * @return $this + */ + public function setAccessToken($accessToken) + { + $this->accessToken = $accessToken; + return $this; + } + + /** + * Gets the access token for OAuth + * + * @return string Access token for OAuth + */ + public function getAccessToken() + { + return $this->accessToken; + } + + /** + * Sets the username for HTTP basic authentication + * + * @param string $username Username for HTTP basic authentication + * + * @return $this + */ + public function setUsername($username) + { + $this->username = $username; + return $this; + } + + /** + * Gets the username for HTTP basic authentication + * + * @return string Username for HTTP basic authentication + */ + public function getUsername() + { + return $this->username; + } + + /** + * Sets the password for HTTP basic authentication + * + * @param string $password Password for HTTP basic authentication + * + * @return $this + */ + public function setPassword($password) + { + $this->password = $password; + return $this; + } + + /** + * Gets the password for HTTP basic authentication + * + * @return string Password for HTTP basic authentication + */ + public function getPassword() + { + return $this->password; + } + + /** + * Sets the host + * + * @param string $host Host + * + * @return $this + */ + public function setHost($host) + { + $this->host = $host; + return $this; + } + + /** + * Gets the host + * + * @return string Host + */ + public function getHost() + { + return $this->host; + } + + /** + * Sets the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * + * @throws \InvalidArgumentException + * @return $this + */ + public function setUserAgent($userAgent) + { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * Gets the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() + { + return $this->userAgent; + } + + /** + * Sets debug flag + * + * @param bool $debug Debug flag + * + * @return $this + */ + public function setDebug($debug) + { + $this->debug = $debug; + return $this; + } + + /** + * Gets the debug flag + * + * @return bool + */ + public function getDebug() + { + return $this->debug; + } + + /** + * Sets the debug file + * + * @param string $debugFile Debug file + * + * @return $this + */ + public function setDebugFile($debugFile) + { + $this->debugFile = $debugFile; + return $this; + } + + /** + * Gets the debug file + * + * @return string + */ + public function getDebugFile() + { + return $this->debugFile; + } + + /** + * Sets the temp folder path + * + * @param string $tempFolderPath Temp folder path + * + * @return $this + */ + public function setTempFolderPath($tempFolderPath) + { + $this->tempFolderPath = $tempFolderPath; + return $this; + } + + /** + * Gets the temp folder path + * + * @return string Temp folder path + */ + public function getTempFolderPath() + { + return $this->tempFolderPath; + } + + /** + * Gets the default configuration instance + * + * @return Configuration + */ + public static function getDefaultConfiguration() + { + if (self::$defaultConfiguration === null) { + self::$defaultConfiguration = new Configuration(); + } + + return self::$defaultConfiguration; + } + + /** + * Sets the detault configuration instance + * + * @param Configuration $config An instance of the Configuration Object + * + * @return void + */ + public static function setDefaultConfiguration(Configuration $config) + { + self::$defaultConfiguration = $config; + } + + /** + * Gets the essential information for debugging + * + * @return string The report for debugging + */ + public static function toDebugReport() + { + $report = 'PHP SDK (Swagger\Client) Debug Report:' . PHP_EOL; + $report .= ' OS: ' . php_uname() . PHP_EOL; + $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; + $report .= ' OpenAPI Spec Version: 1.0.0' . PHP_EOL; + $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; + + return $report; + } + + /** + * Get API key (with prefix if set) + * + * @param string $apiKeyIdentifier name of apikey + * + * @return string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKeyIdentifier) + { + $prefix = $this->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->getApiKey($apiKeyIdentifier); + + if ($apiKey === null) { + return null; + } + + if ($prefix === null) { + $keyWithPrefix = $apiKey; + } else { + $keyWithPrefix = $prefix . ' ' . $apiKey; + } + + return $keyWithPrefix; + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php new file mode 100644 index 000000000000..e0edecf9f5c4 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php @@ -0,0 +1,110 @@ +selectAcceptHeader($accept); + if ($accept !== null) { + $headers['Accept'] = $accept; + } + + $headers['Content-Type'] = $this->selectContentTypeHeader($contentTypes); + return $headers; + } + + /** + * @param string[] $accept + * @return array + */ + public function selectHeadersForMultipart($accept) + { + $headers = $this->selectHeaders($accept, []); + + unset($headers['Content-Type']); + return $headers; + } + + /** + * Return the header 'Accept' based on an array of Accept provided + * + * @param string[] $accept Array of header + * + * @return string Accept (e.g. application/json) + */ + private function selectAcceptHeader($accept) + { + if (count($accept) === 0 || (count($accept) === 1 && $accept[0] === '')) { + return null; + } elseif (preg_grep("/application\/json/i", $accept)) { + return 'application/json'; + } else { + return implode(',', $accept); + } + } + + /** + * Return the content type based on an array of content-type provided + * + * @param string[] $contentType Array fo content-type + * + * @return string Content-Type (e.g. application/json) + */ + private function selectContentTypeHeader($contentType) + { + if (count($contentType) === 0 || (count($contentType) === 1 && $contentType[0] === '')) { + return 'application/json'; + } elseif (preg_grep("/application\/json/i", $contentType)) { + return 'application/json'; + } else { + return implode(',', $contentType); + } + } +} + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php new file mode 100644 index 000000000000..7512ca4e5e4a --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php @@ -0,0 +1,332 @@ + 'map[string,string]', + 'map_of_map_property' => 'map[string,map[string,string]]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'map_property' => null, + 'map_of_map_property' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'map_property' => 'map_property', + 'map_of_map_property' => 'map_of_map_property' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'map_property' => 'setMapProperty', + 'map_of_map_property' => 'setMapOfMapProperty' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'map_property' => 'getMapProperty', + 'map_of_map_property' => 'getMapOfMapProperty' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['map_property'] = isset($data['map_property']) ? $data['map_property'] : null; + $this->container['map_of_map_property'] = isset($data['map_of_map_property']) ? $data['map_of_map_property'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets map_property + * + * @return map[string,string] + */ + public function getMapProperty() + { + return $this->container['map_property']; + } + + /** + * Sets map_property + * + * @param map[string,string] $map_property map_property + * + * @return $this + */ + public function setMapProperty($map_property) + { + $this->container['map_property'] = $map_property; + + return $this; + } + + /** + * Gets map_of_map_property + * + * @return map[string,map[string,string]] + */ + public function getMapOfMapProperty() + { + return $this->container['map_of_map_property']; + } + + /** + * Sets map_of_map_property + * + * @param map[string,map[string,string]] $map_of_map_property map_of_map_property + * + * @return $this + */ + public function setMapOfMapProperty($map_of_map_property) + { + $this->container['map_of_map_property'] = $map_of_map_property; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php new file mode 100644 index 000000000000..aa5f32d9580f --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -0,0 +1,342 @@ + 'string', + 'color' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'class_name' => null, + 'color' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'class_name' => 'className', + 'color' => 'color' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'class_name' => 'setClassName', + 'color' => 'setColor' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'class_name' => 'getClassName', + 'color' => 'getColor' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['class_name'] = isset($data['class_name']) ? $data['class_name'] : null; + $this->container['color'] = isset($data['color']) ? $data['color'] : 'red'; + + // Initialize discriminator property with the model name. + $discriminator = array_search('className', self::$attributeMap); + $this->container[$discriminator] = static::$swaggerModelName; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + if ($this->container['class_name'] === null) { + $invalidProperties[] = "'class_name' can't be null"; + } + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + if ($this->container['class_name'] === null) { + return false; + } + return true; + } + + + /** + * Gets class_name + * + * @return string + */ + public function getClassName() + { + return $this->container['class_name']; + } + + /** + * Sets class_name + * + * @param string $class_name class_name + * + * @return $this + */ + public function setClassName($class_name) + { + $this->container['class_name'] = $class_name; + + return $this; + } + + /** + * Gets color + * + * @return string + */ + public function getColor() + { + return $this->container['color']; + } + + /** + * Sets color + * + * @param string $color color + * + * @return $this + */ + public function setColor($color) + { + $this->container['color'] = $color; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php new file mode 100644 index 000000000000..acb677b8c005 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -0,0 +1,280 @@ +container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php new file mode 100644 index 000000000000..8d205cc68bb3 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -0,0 +1,362 @@ + 'int', + 'type' => 'string', + 'message' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'code' => 'int32', + 'type' => null, + 'message' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'code' => 'code', + 'type' => 'type', + 'message' => 'message' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'code' => 'setCode', + 'type' => 'setType', + 'message' => 'setMessage' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'code' => 'getCode', + 'type' => 'getType', + 'message' => 'getMessage' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['code'] = isset($data['code']) ? $data['code'] : null; + $this->container['type'] = isset($data['type']) ? $data['type'] : null; + $this->container['message'] = isset($data['message']) ? $data['message'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets code + * + * @return int + */ + public function getCode() + { + return $this->container['code']; + } + + /** + * Sets code + * + * @param int $code code + * + * @return $this + */ + public function setCode($code) + { + $this->container['code'] = $code; + + return $this; + } + + /** + * Gets type + * + * @return string + */ + public function getType() + { + return $this->container['type']; + } + + /** + * Sets type + * + * @param string $type type + * + * @return $this + */ + public function setType($type) + { + $this->container['type'] = $type; + + return $this; + } + + /** + * Gets message + * + * @return string + */ + public function getMessage() + { + return $this->container['message']; + } + + /** + * Sets message + * + * @param string $message message + * + * @return $this + */ + public function setMessage($message) + { + $this->container['message'] = $message; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php new file mode 100644 index 000000000000..6b1bd4f6e898 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -0,0 +1,302 @@ + 'float[][]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'array_array_number' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'array_array_number' => 'ArrayArrayNumber' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'array_array_number' => 'setArrayArrayNumber' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'array_array_number' => 'getArrayArrayNumber' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['array_array_number'] = isset($data['array_array_number']) ? $data['array_array_number'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets array_array_number + * + * @return float[][] + */ + public function getArrayArrayNumber() + { + return $this->container['array_array_number']; + } + + /** + * Sets array_array_number + * + * @param float[][] $array_array_number array_array_number + * + * @return $this + */ + public function setArrayArrayNumber($array_array_number) + { + $this->container['array_array_number'] = $array_array_number; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php new file mode 100644 index 000000000000..9d757dc67c0d --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php @@ -0,0 +1,302 @@ + 'float[]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'array_number' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'array_number' => 'ArrayNumber' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'array_number' => 'setArrayNumber' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'array_number' => 'getArrayNumber' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['array_number'] = isset($data['array_number']) ? $data['array_number'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets array_number + * + * @return float[] + */ + public function getArrayNumber() + { + return $this->container['array_number']; + } + + /** + * Sets array_number + * + * @param float[] $array_number array_number + * + * @return $this + */ + public function setArrayNumber($array_number) + { + $this->container['array_number'] = $array_number; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php new file mode 100644 index 000000000000..b2152d435c29 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php @@ -0,0 +1,362 @@ + 'string[]', + 'array_array_of_integer' => 'int[][]', + 'array_array_of_model' => '\Swagger\Client\Model\ReadOnlyFirst[][]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'array_of_string' => null, + 'array_array_of_integer' => 'int64', + 'array_array_of_model' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'array_of_string' => 'array_of_string', + 'array_array_of_integer' => 'array_array_of_integer', + 'array_array_of_model' => 'array_array_of_model' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'array_of_string' => 'setArrayOfString', + 'array_array_of_integer' => 'setArrayArrayOfInteger', + 'array_array_of_model' => 'setArrayArrayOfModel' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'array_of_string' => 'getArrayOfString', + 'array_array_of_integer' => 'getArrayArrayOfInteger', + 'array_array_of_model' => 'getArrayArrayOfModel' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['array_of_string'] = isset($data['array_of_string']) ? $data['array_of_string'] : null; + $this->container['array_array_of_integer'] = isset($data['array_array_of_integer']) ? $data['array_array_of_integer'] : null; + $this->container['array_array_of_model'] = isset($data['array_array_of_model']) ? $data['array_array_of_model'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets array_of_string + * + * @return string[] + */ + public function getArrayOfString() + { + return $this->container['array_of_string']; + } + + /** + * Sets array_of_string + * + * @param string[] $array_of_string array_of_string + * + * @return $this + */ + public function setArrayOfString($array_of_string) + { + $this->container['array_of_string'] = $array_of_string; + + return $this; + } + + /** + * Gets array_array_of_integer + * + * @return int[][] + */ + public function getArrayArrayOfInteger() + { + return $this->container['array_array_of_integer']; + } + + /** + * Sets array_array_of_integer + * + * @param int[][] $array_array_of_integer array_array_of_integer + * + * @return $this + */ + public function setArrayArrayOfInteger($array_array_of_integer) + { + $this->container['array_array_of_integer'] = $array_array_of_integer; + + return $this; + } + + /** + * Gets array_array_of_model + * + * @return \Swagger\Client\Model\ReadOnlyFirst[][] + */ + public function getArrayArrayOfModel() + { + return $this->container['array_array_of_model']; + } + + /** + * Sets array_array_of_model + * + * @param \Swagger\Client\Model\ReadOnlyFirst[][] $array_array_of_model array_array_of_model + * + * @return $this + */ + public function setArrayArrayOfModel($array_array_of_model) + { + $this->container['array_array_of_model'] = $array_array_of_model; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body.php new file mode 100644 index 000000000000..7b979a828221 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body.php @@ -0,0 +1,332 @@ + 'string', + 'status' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'name' => null, + 'status' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'name' => 'name', + 'status' => 'status' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'name' => 'setName', + 'status' => 'setStatus' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'name' => 'getName', + 'status' => 'getStatus' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['name'] = isset($data['name']) ? $data['name'] : null; + $this->container['status'] = isset($data['status']) ? $data['status'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets name + * + * @return string + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param string $name Updated name of the pet + * + * @return $this + */ + public function setName($name) + { + $this->container['name'] = $name; + + return $this; + } + + /** + * Gets status + * + * @return string + */ + public function getStatus() + { + return $this->container['status']; + } + + /** + * Sets status + * + * @param string $status Updated status of the pet + * + * @return $this + */ + public function setStatus($status) + { + $this->container['status'] = $status; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body1.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body1.php new file mode 100644 index 000000000000..4f68b229dff4 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body1.php @@ -0,0 +1,332 @@ + 'string', + 'file' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'additional_metadata' => null, + 'file' => 'binary' + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'additional_metadata' => 'additionalMetadata', + 'file' => 'file' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'additional_metadata' => 'setAdditionalMetadata', + 'file' => 'setFile' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'additional_metadata' => 'getAdditionalMetadata', + 'file' => 'getFile' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['additional_metadata'] = isset($data['additional_metadata']) ? $data['additional_metadata'] : null; + $this->container['file'] = isset($data['file']) ? $data['file'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets additional_metadata + * + * @return string + */ + public function getAdditionalMetadata() + { + return $this->container['additional_metadata']; + } + + /** + * Sets additional_metadata + * + * @param string $additional_metadata Additional data to pass to server + * + * @return $this + */ + public function setAdditionalMetadata($additional_metadata) + { + $this->container['additional_metadata'] = $additional_metadata; + + return $this; + } + + /** + * Gets file + * + * @return string + */ + public function getFile() + { + return $this->container['file']; + } + + /** + * Sets file + * + * @param string $file file to upload + * + * @return $this + */ + public function setFile($file) + { + $this->container['file'] = $file; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body2.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body2.php new file mode 100644 index 000000000000..1f53bc2849a1 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body2.php @@ -0,0 +1,394 @@ + 'string[]', + 'enum_form_string' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'enum_form_string_array' => null, + 'enum_form_string' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'enum_form_string_array' => 'enum_form_string_array', + 'enum_form_string' => 'enum_form_string' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'enum_form_string_array' => 'setEnumFormStringArray', + 'enum_form_string' => 'setEnumFormString' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'enum_form_string_array' => 'getEnumFormStringArray', + 'enum_form_string' => 'getEnumFormString' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + const ENUM_FORM_STRING_ARRAY_GREATER_THAN = '>'; + const ENUM_FORM_STRING_ARRAY_DOLLAR = '$'; + const ENUM_FORM_STRING_ABC = '_abc'; + const ENUM_FORM_STRING_EFG = '-efg'; + const ENUM_FORM_STRING_XYZ = '(xyz)'; + + + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getEnumFormStringArrayAllowableValues() + { + return [ + self::ENUM_FORM_STRING_ARRAY_GREATER_THAN, + self::ENUM_FORM_STRING_ARRAY_DOLLAR, + ]; + } + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getEnumFormStringAllowableValues() + { + return [ + self::ENUM_FORM_STRING_ABC, + self::ENUM_FORM_STRING_EFG, + self::ENUM_FORM_STRING_XYZ, + ]; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['enum_form_string_array'] = isset($data['enum_form_string_array']) ? $data['enum_form_string_array'] : null; + $this->container['enum_form_string'] = isset($data['enum_form_string']) ? $data['enum_form_string'] : '-efg'; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + $allowedValues = $this->getEnumFormStringAllowableValues(); + if (!is_null($this->container['enum_form_string']) && !in_array($this->container['enum_form_string'], $allowedValues, true)) { + $invalidProperties[] = sprintf( + "invalid value for 'enum_form_string', must be one of '%s'", + implode("', '", $allowedValues) + ); + } + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + $allowedValues = $this->getEnumFormStringAllowableValues(); + if (!is_null($this->container['enum_form_string']) && !in_array($this->container['enum_form_string'], $allowedValues, true)) { + return false; + } + return true; + } + + + /** + * Gets enum_form_string_array + * + * @return string[] + */ + public function getEnumFormStringArray() + { + return $this->container['enum_form_string_array']; + } + + /** + * Sets enum_form_string_array + * + * @param string[] $enum_form_string_array Form parameter enum test (string array) + * + * @return $this + */ + public function setEnumFormStringArray($enum_form_string_array) + { + $allowedValues = $this->getEnumFormStringArrayAllowableValues(); + if (!is_null($enum_form_string_array) && array_diff($enum_form_string_array, $allowedValues)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value for 'enum_form_string_array', must be one of '%s'", + implode("', '", $allowedValues) + ) + ); + } + $this->container['enum_form_string_array'] = $enum_form_string_array; + + return $this; + } + + /** + * Gets enum_form_string + * + * @return string + */ + public function getEnumFormString() + { + return $this->container['enum_form_string']; + } + + /** + * Sets enum_form_string + * + * @param string $enum_form_string Form parameter enum test (string) + * + * @return $this + */ + public function setEnumFormString($enum_form_string) + { + $allowedValues = $this->getEnumFormStringAllowableValues(); + if (!is_null($enum_form_string) && !in_array($enum_form_string, $allowedValues, true)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value for 'enum_form_string', must be one of '%s'", + implode("', '", $allowedValues) + ) + ); + } + $this->container['enum_form_string'] = $enum_form_string; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body3.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body3.php new file mode 100644 index 000000000000..cf6c0709d8d2 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body3.php @@ -0,0 +1,781 @@ + 'int', + 'int32' => 'int', + 'int64' => 'int', + 'number' => 'BigDecimal', + 'float' => 'float', + 'double' => 'double', + 'string' => 'string', + 'pattern_without_delimiter' => 'string', + 'byte' => 'string', + 'binary' => 'string', + 'date' => '\DateTime', + 'date_time' => '\DateTime', + 'password' => 'string', + 'callback' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'integer' => 'int32', + 'int32' => 'int32', + 'int64' => 'int64', + 'number' => null, + 'float' => 'float', + 'double' => 'double', + 'string' => null, + 'pattern_without_delimiter' => null, + 'byte' => 'byte', + 'binary' => 'binary', + 'date' => 'date', + 'date_time' => 'date-time', + 'password' => 'password', + 'callback' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'integer' => 'integer', + 'int32' => 'int32', + 'int64' => 'int64', + 'number' => 'number', + 'float' => 'float', + 'double' => 'double', + 'string' => 'string', + 'pattern_without_delimiter' => 'pattern_without_delimiter', + 'byte' => 'byte', + 'binary' => 'binary', + 'date' => 'date', + 'date_time' => 'dateTime', + 'password' => 'password', + 'callback' => 'callback' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'integer' => 'setInteger', + 'int32' => 'setInt32', + 'int64' => 'setInt64', + 'number' => 'setNumber', + 'float' => 'setFloat', + 'double' => 'setDouble', + 'string' => 'setString', + 'pattern_without_delimiter' => 'setPatternWithoutDelimiter', + 'byte' => 'setByte', + 'binary' => 'setBinary', + 'date' => 'setDate', + 'date_time' => 'setDateTime', + 'password' => 'setPassword', + 'callback' => 'setCallback' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'integer' => 'getInteger', + 'int32' => 'getInt32', + 'int64' => 'getInt64', + 'number' => 'getNumber', + 'float' => 'getFloat', + 'double' => 'getDouble', + 'string' => 'getString', + 'pattern_without_delimiter' => 'getPatternWithoutDelimiter', + 'byte' => 'getByte', + 'binary' => 'getBinary', + 'date' => 'getDate', + 'date_time' => 'getDateTime', + 'password' => 'getPassword', + 'callback' => 'getCallback' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['integer'] = isset($data['integer']) ? $data['integer'] : null; + $this->container['int32'] = isset($data['int32']) ? $data['int32'] : null; + $this->container['int64'] = isset($data['int64']) ? $data['int64'] : null; + $this->container['number'] = isset($data['number']) ? $data['number'] : null; + $this->container['float'] = isset($data['float']) ? $data['float'] : null; + $this->container['double'] = isset($data['double']) ? $data['double'] : null; + $this->container['string'] = isset($data['string']) ? $data['string'] : null; + $this->container['pattern_without_delimiter'] = isset($data['pattern_without_delimiter']) ? $data['pattern_without_delimiter'] : null; + $this->container['byte'] = isset($data['byte']) ? $data['byte'] : null; + $this->container['binary'] = isset($data['binary']) ? $data['binary'] : null; + $this->container['date'] = isset($data['date']) ? $data['date'] : null; + $this->container['date_time'] = isset($data['date_time']) ? $data['date_time'] : null; + $this->container['password'] = isset($data['password']) ? $data['password'] : null; + $this->container['callback'] = isset($data['callback']) ? $data['callback'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + if (!is_null($this->container['integer']) && ($this->container['integer'] > 100)) { + $invalidProperties[] = "invalid value for 'integer', must be smaller than or equal to 100."; + } + + if (!is_null($this->container['integer']) && ($this->container['integer'] < 10)) { + $invalidProperties[] = "invalid value for 'integer', must be bigger than or equal to 10."; + } + + if (!is_null($this->container['int32']) && ($this->container['int32'] > 200)) { + $invalidProperties[] = "invalid value for 'int32', must be smaller than or equal to 200."; + } + + if (!is_null($this->container['int32']) && ($this->container['int32'] < 20)) { + $invalidProperties[] = "invalid value for 'int32', must be bigger than or equal to 20."; + } + + if ($this->container['number'] === null) { + $invalidProperties[] = "'number' can't be null"; + } + if ($this->container['double'] === null) { + $invalidProperties[] = "'double' can't be null"; + } + if ($this->container['pattern_without_delimiter'] === null) { + $invalidProperties[] = "'pattern_without_delimiter' can't be null"; + } + if ($this->container['byte'] === null) { + $invalidProperties[] = "'byte' can't be null"; + } + if (!is_null($this->container['password']) && (mb_strlen($this->container['password']) > 64)) { + $invalidProperties[] = "invalid value for 'password', the character length must be smaller than or equal to 64."; + } + + if (!is_null($this->container['password']) && (mb_strlen($this->container['password']) < 10)) { + $invalidProperties[] = "invalid value for 'password', the character length must be bigger than or equal to 10."; + } + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + if ($this->container['integer'] > 100) { + return false; + } + if ($this->container['integer'] < 10) { + return false; + } + if ($this->container['int32'] > 200) { + return false; + } + if ($this->container['int32'] < 20) { + return false; + } + if ($this->container['number'] === null) { + return false; + } + if ($this->container['double'] === null) { + return false; + } + if ($this->container['pattern_without_delimiter'] === null) { + return false; + } + if ($this->container['byte'] === null) { + return false; + } + if (mb_strlen($this->container['password']) > 64) { + return false; + } + if (mb_strlen($this->container['password']) < 10) { + return false; + } + return true; + } + + + /** + * Gets integer + * + * @return int + */ + public function getInteger() + { + return $this->container['integer']; + } + + /** + * Sets integer + * + * @param int $integer None + * + * @return $this + */ + public function setInteger($integer) + { + + if (!is_null($integer) && ($integer > 100)) { + throw new \InvalidArgumentException('invalid value for $integer when calling Body3., must be smaller than or equal to 100.'); + } + if (!is_null($integer) && ($integer < 10)) { + throw new \InvalidArgumentException('invalid value for $integer when calling Body3., must be bigger than or equal to 10.'); + } + + $this->container['integer'] = $integer; + + return $this; + } + + /** + * Gets int32 + * + * @return int + */ + public function getInt32() + { + return $this->container['int32']; + } + + /** + * Sets int32 + * + * @param int $int32 None + * + * @return $this + */ + public function setInt32($int32) + { + + if (!is_null($int32) && ($int32 > 200)) { + throw new \InvalidArgumentException('invalid value for $int32 when calling Body3., must be smaller than or equal to 200.'); + } + if (!is_null($int32) && ($int32 < 20)) { + throw new \InvalidArgumentException('invalid value for $int32 when calling Body3., must be bigger than or equal to 20.'); + } + + $this->container['int32'] = $int32; + + return $this; + } + + /** + * Gets int64 + * + * @return int + */ + public function getInt64() + { + return $this->container['int64']; + } + + /** + * Sets int64 + * + * @param int $int64 None + * + * @return $this + */ + public function setInt64($int64) + { + $this->container['int64'] = $int64; + + return $this; + } + + /** + * Gets number + * + * @return BigDecimal + */ + public function getNumber() + { + return $this->container['number']; + } + + /** + * Sets number + * + * @param BigDecimal $number None + * + * @return $this + */ + public function setNumber($number) + { + $this->container['number'] = $number; + + return $this; + } + + /** + * Gets float + * + * @return float + */ + public function getFloat() + { + return $this->container['float']; + } + + /** + * Sets float + * + * @param float $float None + * + * @return $this + */ + public function setFloat($float) + { + $this->container['float'] = $float; + + return $this; + } + + /** + * Gets double + * + * @return double + */ + public function getDouble() + { + return $this->container['double']; + } + + /** + * Sets double + * + * @param double $double None + * + * @return $this + */ + public function setDouble($double) + { + $this->container['double'] = $double; + + return $this; + } + + /** + * Gets string + * + * @return string + */ + public function getString() + { + return $this->container['string']; + } + + /** + * Sets string + * + * @param string $string None + * + * @return $this + */ + public function setString($string) + { + $this->container['string'] = $string; + + return $this; + } + + /** + * Gets pattern_without_delimiter + * + * @return string + */ + public function getPatternWithoutDelimiter() + { + return $this->container['pattern_without_delimiter']; + } + + /** + * Sets pattern_without_delimiter + * + * @param string $pattern_without_delimiter None + * + * @return $this + */ + public function setPatternWithoutDelimiter($pattern_without_delimiter) + { + $this->container['pattern_without_delimiter'] = $pattern_without_delimiter; + + return $this; + } + + /** + * Gets byte + * + * @return string + */ + public function getByte() + { + return $this->container['byte']; + } + + /** + * Sets byte + * + * @param string $byte None + * + * @return $this + */ + public function setByte($byte) + { + $this->container['byte'] = $byte; + + return $this; + } + + /** + * Gets binary + * + * @return string + */ + public function getBinary() + { + return $this->container['binary']; + } + + /** + * Sets binary + * + * @param string $binary None + * + * @return $this + */ + public function setBinary($binary) + { + $this->container['binary'] = $binary; + + return $this; + } + + /** + * Gets date + * + * @return \DateTime + */ + public function getDate() + { + return $this->container['date']; + } + + /** + * Sets date + * + * @param \DateTime $date None + * + * @return $this + */ + public function setDate($date) + { + $this->container['date'] = $date; + + return $this; + } + + /** + * Gets date_time + * + * @return \DateTime + */ + public function getDateTime() + { + return $this->container['date_time']; + } + + /** + * Sets date_time + * + * @param \DateTime $date_time None + * + * @return $this + */ + public function setDateTime($date_time) + { + $this->container['date_time'] = $date_time; + + return $this; + } + + /** + * Gets password + * + * @return string + */ + public function getPassword() + { + return $this->container['password']; + } + + /** + * Sets password + * + * @param string $password None + * + * @return $this + */ + public function setPassword($password) + { + if (!is_null($password) && (mb_strlen($password) > 64)) { + throw new \InvalidArgumentException('invalid length for $password when calling Body3., must be smaller than or equal to 64.'); + } + if (!is_null($password) && (mb_strlen($password) < 10)) { + throw new \InvalidArgumentException('invalid length for $password when calling Body3., must be bigger than or equal to 10.'); + } + + $this->container['password'] = $password; + + return $this; + } + + /** + * Gets callback + * + * @return string + */ + public function getCallback() + { + return $this->container['callback']; + } + + /** + * Sets callback + * + * @param string $callback None + * + * @return $this + */ + public function setCallback($callback) + { + $this->container['callback'] = $callback; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body4.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body4.php new file mode 100644 index 000000000000..9420b3212a44 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Body4.php @@ -0,0 +1,344 @@ + 'string', + 'param2' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'param' => null, + 'param2' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'param' => 'param', + 'param2' => 'param2' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'param' => 'setParam', + 'param2' => 'setParam2' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'param' => 'getParam', + 'param2' => 'getParam2' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['param'] = isset($data['param']) ? $data['param'] : null; + $this->container['param2'] = isset($data['param2']) ? $data['param2'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + if ($this->container['param'] === null) { + $invalidProperties[] = "'param' can't be null"; + } + if ($this->container['param2'] === null) { + $invalidProperties[] = "'param2' can't be null"; + } + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + if ($this->container['param'] === null) { + return false; + } + if ($this->container['param2'] === null) { + return false; + } + return true; + } + + + /** + * Gets param + * + * @return string + */ + public function getParam() + { + return $this->container['param']; + } + + /** + * Sets param + * + * @param string $param field1 + * + * @return $this + */ + public function setParam($param) + { + $this->container['param'] = $param; + + return $this; + } + + /** + * Gets param2 + * + * @return string + */ + public function getParam2() + { + return $this->container['param2']; + } + + /** + * Sets param2 + * + * @param string $param2 field2 + * + * @return $this + */ + public function setParam2($param2) + { + $this->container['param2'] = $param2; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Capitalization.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Capitalization.php new file mode 100644 index 000000000000..cda89021f91d --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Capitalization.php @@ -0,0 +1,452 @@ + 'string', + 'capital_camel' => 'string', + 'small_snake' => 'string', + 'capital_snake' => 'string', + 'sca_eth_flow_points' => 'string', + 'att_name' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'small_camel' => null, + 'capital_camel' => null, + 'small_snake' => null, + 'capital_snake' => null, + 'sca_eth_flow_points' => null, + 'att_name' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'small_camel' => 'smallCamel', + 'capital_camel' => 'CapitalCamel', + 'small_snake' => 'small_Snake', + 'capital_snake' => 'Capital_Snake', + 'sca_eth_flow_points' => 'SCA_ETH_Flow_Points', + 'att_name' => 'ATT_NAME' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'small_camel' => 'setSmallCamel', + 'capital_camel' => 'setCapitalCamel', + 'small_snake' => 'setSmallSnake', + 'capital_snake' => 'setCapitalSnake', + 'sca_eth_flow_points' => 'setScaEthFlowPoints', + 'att_name' => 'setAttName' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'small_camel' => 'getSmallCamel', + 'capital_camel' => 'getCapitalCamel', + 'small_snake' => 'getSmallSnake', + 'capital_snake' => 'getCapitalSnake', + 'sca_eth_flow_points' => 'getScaEthFlowPoints', + 'att_name' => 'getAttName' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['small_camel'] = isset($data['small_camel']) ? $data['small_camel'] : null; + $this->container['capital_camel'] = isset($data['capital_camel']) ? $data['capital_camel'] : null; + $this->container['small_snake'] = isset($data['small_snake']) ? $data['small_snake'] : null; + $this->container['capital_snake'] = isset($data['capital_snake']) ? $data['capital_snake'] : null; + $this->container['sca_eth_flow_points'] = isset($data['sca_eth_flow_points']) ? $data['sca_eth_flow_points'] : null; + $this->container['att_name'] = isset($data['att_name']) ? $data['att_name'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets small_camel + * + * @return string + */ + public function getSmallCamel() + { + return $this->container['small_camel']; + } + + /** + * Sets small_camel + * + * @param string $small_camel small_camel + * + * @return $this + */ + public function setSmallCamel($small_camel) + { + $this->container['small_camel'] = $small_camel; + + return $this; + } + + /** + * Gets capital_camel + * + * @return string + */ + public function getCapitalCamel() + { + return $this->container['capital_camel']; + } + + /** + * Sets capital_camel + * + * @param string $capital_camel capital_camel + * + * @return $this + */ + public function setCapitalCamel($capital_camel) + { + $this->container['capital_camel'] = $capital_camel; + + return $this; + } + + /** + * Gets small_snake + * + * @return string + */ + public function getSmallSnake() + { + return $this->container['small_snake']; + } + + /** + * Sets small_snake + * + * @param string $small_snake small_snake + * + * @return $this + */ + public function setSmallSnake($small_snake) + { + $this->container['small_snake'] = $small_snake; + + return $this; + } + + /** + * Gets capital_snake + * + * @return string + */ + public function getCapitalSnake() + { + return $this->container['capital_snake']; + } + + /** + * Sets capital_snake + * + * @param string $capital_snake capital_snake + * + * @return $this + */ + public function setCapitalSnake($capital_snake) + { + $this->container['capital_snake'] = $capital_snake; + + return $this; + } + + /** + * Gets sca_eth_flow_points + * + * @return string + */ + public function getScaEthFlowPoints() + { + return $this->container['sca_eth_flow_points']; + } + + /** + * Sets sca_eth_flow_points + * + * @param string $sca_eth_flow_points sca_eth_flow_points + * + * @return $this + */ + public function setScaEthFlowPoints($sca_eth_flow_points) + { + $this->container['sca_eth_flow_points'] = $sca_eth_flow_points; + + return $this; + } + + /** + * Gets att_name + * + * @return string + */ + public function getAttName() + { + return $this->container['att_name']; + } + + /** + * Sets att_name + * + * @param string $att_name Name of the pet + * + * @return $this + */ + public function setAttName($att_name) + { + $this->container['att_name'] = $att_name; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php new file mode 100644 index 000000000000..00a34932a2d2 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -0,0 +1,299 @@ + 'bool' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'declawed' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes + parent::swaggerTypes(); + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats + parent::swaggerFormats(); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'declawed' => 'declawed' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'declawed' => 'setDeclawed' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'declawed' => 'getDeclawed' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return parent::attributeMap() + self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return parent::setters() + self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return parent::getters() + self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + parent::__construct($data); + + $this->container['declawed'] = isset($data['declawed']) ? $data['declawed'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = parent::listInvalidProperties(); + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + if (!parent::valid()) { + return false; + } + + return true; + } + + + /** + * Gets declawed + * + * @return bool + */ + public function getDeclawed() + { + return $this->container['declawed']; + } + + /** + * Sets declawed + * + * @param bool $declawed declawed + * + * @return $this + */ + public function setDeclawed($declawed) + { + $this->container['declawed'] = $declawed; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Category.php new file mode 100644 index 000000000000..32f77c580d89 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -0,0 +1,332 @@ + 'int', + 'name' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'id' => 'int64', + 'name' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'id' => 'id', + 'name' => 'name' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'id' => 'setId', + 'name' => 'setName' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'id' => 'getId', + 'name' => 'getName' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['name'] = isset($data['name']) ? $data['name'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets id + * + * @return int + */ + public function getId() + { + return $this->container['id']; + } + + /** + * Sets id + * + * @param int $id id + * + * @return $this + */ + public function setId($id) + { + $this->container['id'] = $id; + + return $this; + } + + /** + * Gets name + * + * @return string + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param string $name name + * + * @return $this + */ + public function setName($name) + { + $this->container['name'] = $name; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ClassModel.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ClassModel.php new file mode 100644 index 000000000000..5ad46465baf0 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ClassModel.php @@ -0,0 +1,303 @@ + 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + '_class' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + '_class' => '_class' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + '_class' => 'setClass' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + '_class' => 'getClass' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['_class'] = isset($data['_class']) ? $data['_class'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets _class + * + * @return string + */ + public function getClass() + { + return $this->container['_class']; + } + + /** + * Sets _class + * + * @param string $_class _class + * + * @return $this + */ + public function setClass($_class) + { + $this->container['_class'] = $_class; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Client.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Client.php new file mode 100644 index 000000000000..2acdd8aadaac --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Client.php @@ -0,0 +1,302 @@ + 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'client' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'client' => 'client' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'client' => 'setClient' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'client' => 'getClient' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['client'] = isset($data['client']) ? $data['client'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets client + * + * @return string + */ + public function getClient() + { + return $this->container['client']; + } + + /** + * Sets client + * + * @param string $client client + * + * @return $this + */ + public function setClient($client) + { + $this->container['client'] = $client; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php new file mode 100644 index 000000000000..5caf83b8304e --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -0,0 +1,299 @@ + 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'breed' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes + parent::swaggerTypes(); + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats + parent::swaggerFormats(); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'breed' => 'breed' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'breed' => 'setBreed' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'breed' => 'getBreed' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return parent::attributeMap() + self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return parent::setters() + self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return parent::getters() + self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + parent::__construct($data); + + $this->container['breed'] = isset($data['breed']) ? $data['breed'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = parent::listInvalidProperties(); + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + if (!parent::valid()) { + return false; + } + + return true; + } + + + /** + * Gets breed + * + * @return string + */ + public function getBreed() + { + return $this->container['breed']; + } + + /** + * Sets breed + * + * @param string $breed breed + * + * @return $this + */ + public function setBreed($breed) + { + $this->container['breed'] = $breed; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php new file mode 100644 index 000000000000..26a6c705d49b --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php @@ -0,0 +1,392 @@ + 'string', + 'array_enum' => 'string[]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'just_symbol' => null, + 'array_enum' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'just_symbol' => 'just_symbol', + 'array_enum' => 'array_enum' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'just_symbol' => 'setJustSymbol', + 'array_enum' => 'setArrayEnum' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'just_symbol' => 'getJustSymbol', + 'array_enum' => 'getArrayEnum' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + const JUST_SYMBOL_GREATER_THAN_OR_EQUAL_TO = '>='; + const JUST_SYMBOL_DOLLAR = '$'; + const ARRAY_ENUM_FISH = 'fish'; + const ARRAY_ENUM_CRAB = 'crab'; + + + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getJustSymbolAllowableValues() + { + return [ + self::JUST_SYMBOL_GREATER_THAN_OR_EQUAL_TO, + self::JUST_SYMBOL_DOLLAR, + ]; + } + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getArrayEnumAllowableValues() + { + return [ + self::ARRAY_ENUM_FISH, + self::ARRAY_ENUM_CRAB, + ]; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['just_symbol'] = isset($data['just_symbol']) ? $data['just_symbol'] : null; + $this->container['array_enum'] = isset($data['array_enum']) ? $data['array_enum'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + $allowedValues = $this->getJustSymbolAllowableValues(); + if (!is_null($this->container['just_symbol']) && !in_array($this->container['just_symbol'], $allowedValues, true)) { + $invalidProperties[] = sprintf( + "invalid value for 'just_symbol', must be one of '%s'", + implode("', '", $allowedValues) + ); + } + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + $allowedValues = $this->getJustSymbolAllowableValues(); + if (!is_null($this->container['just_symbol']) && !in_array($this->container['just_symbol'], $allowedValues, true)) { + return false; + } + return true; + } + + + /** + * Gets just_symbol + * + * @return string + */ + public function getJustSymbol() + { + return $this->container['just_symbol']; + } + + /** + * Sets just_symbol + * + * @param string $just_symbol just_symbol + * + * @return $this + */ + public function setJustSymbol($just_symbol) + { + $allowedValues = $this->getJustSymbolAllowableValues(); + if (!is_null($just_symbol) && !in_array($just_symbol, $allowedValues, true)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value for 'just_symbol', must be one of '%s'", + implode("', '", $allowedValues) + ) + ); + } + $this->container['just_symbol'] = $just_symbol; + + return $this; + } + + /** + * Gets array_enum + * + * @return string[] + */ + public function getArrayEnum() + { + return $this->container['array_enum']; + } + + /** + * Sets array_enum + * + * @param string[] $array_enum array_enum + * + * @return $this + */ + public function setArrayEnum($array_enum) + { + $allowedValues = $this->getArrayEnumAllowableValues(); + if (!is_null($array_enum) && array_diff($array_enum, $allowedValues)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value for 'array_enum', must be one of '%s'", + implode("', '", $allowedValues) + ) + ); + } + $this->container['array_enum'] = $array_enum; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php new file mode 100644 index 000000000000..6975bc6c8074 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php @@ -0,0 +1,64 @@ + 'string', + 'enum_string_required' => 'string', + 'enum_integer' => 'int', + 'enum_number' => 'double', + 'outer_enum' => '\Swagger\Client\Model\OuterEnum' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'enum_string' => null, + 'enum_string_required' => null, + 'enum_integer' => 'int32', + 'enum_number' => 'double', + 'outer_enum' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'enum_string' => 'enum_string', + 'enum_string_required' => 'enum_string_required', + 'enum_integer' => 'enum_integer', + 'enum_number' => 'enum_number', + 'outer_enum' => 'outerEnum' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'enum_string' => 'setEnumString', + 'enum_string_required' => 'setEnumStringRequired', + 'enum_integer' => 'setEnumInteger', + 'enum_number' => 'setEnumNumber', + 'outer_enum' => 'setOuterEnum' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'enum_string' => 'getEnumString', + 'enum_string_required' => 'getEnumStringRequired', + 'enum_integer' => 'getEnumInteger', + 'enum_number' => 'getEnumNumber', + 'outer_enum' => 'getOuterEnum' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + const ENUM_STRING_UPPER = 'UPPER'; + const ENUM_STRING_LOWER = 'lower'; + const ENUM_STRING_EMPTY = ''; + const ENUM_STRING_REQUIRED_UPPER = 'UPPER'; + const ENUM_STRING_REQUIRED_LOWER = 'lower'; + const ENUM_STRING_REQUIRED_EMPTY = ''; + const ENUM_INTEGER_1 = 1; + const ENUM_INTEGER_MINUS_1 = -1; + const ENUM_NUMBER_1_DOT_1 = 1.1; + const ENUM_NUMBER_MINUS_1_DOT_2 = -1.2; + + + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getEnumStringAllowableValues() + { + return [ + self::ENUM_STRING_UPPER, + self::ENUM_STRING_LOWER, + self::ENUM_STRING_EMPTY, + ]; + } + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getEnumStringRequiredAllowableValues() + { + return [ + self::ENUM_STRING_REQUIRED_UPPER, + self::ENUM_STRING_REQUIRED_LOWER, + self::ENUM_STRING_REQUIRED_EMPTY, + ]; + } + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getEnumIntegerAllowableValues() + { + return [ + self::ENUM_INTEGER_1, + self::ENUM_INTEGER_MINUS_1, + ]; + } + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getEnumNumberAllowableValues() + { + return [ + self::ENUM_NUMBER_1_DOT_1, + self::ENUM_NUMBER_MINUS_1_DOT_2, + ]; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['enum_string'] = isset($data['enum_string']) ? $data['enum_string'] : null; + $this->container['enum_string_required'] = isset($data['enum_string_required']) ? $data['enum_string_required'] : null; + $this->container['enum_integer'] = isset($data['enum_integer']) ? $data['enum_integer'] : null; + $this->container['enum_number'] = isset($data['enum_number']) ? $data['enum_number'] : null; + $this->container['outer_enum'] = isset($data['outer_enum']) ? $data['outer_enum'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + $allowedValues = $this->getEnumStringAllowableValues(); + if (!is_null($this->container['enum_string']) && !in_array($this->container['enum_string'], $allowedValues, true)) { + $invalidProperties[] = sprintf( + "invalid value for 'enum_string', must be one of '%s'", + implode("', '", $allowedValues) + ); + } + + if ($this->container['enum_string_required'] === null) { + $invalidProperties[] = "'enum_string_required' can't be null"; + } + $allowedValues = $this->getEnumStringRequiredAllowableValues(); + if (!is_null($this->container['enum_string_required']) && !in_array($this->container['enum_string_required'], $allowedValues, true)) { + $invalidProperties[] = sprintf( + "invalid value for 'enum_string_required', must be one of '%s'", + implode("', '", $allowedValues) + ); + } + + $allowedValues = $this->getEnumIntegerAllowableValues(); + if (!is_null($this->container['enum_integer']) && !in_array($this->container['enum_integer'], $allowedValues, true)) { + $invalidProperties[] = sprintf( + "invalid value for 'enum_integer', must be one of '%s'", + implode("', '", $allowedValues) + ); + } + + $allowedValues = $this->getEnumNumberAllowableValues(); + if (!is_null($this->container['enum_number']) && !in_array($this->container['enum_number'], $allowedValues, true)) { + $invalidProperties[] = sprintf( + "invalid value for 'enum_number', must be one of '%s'", + implode("', '", $allowedValues) + ); + } + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + $allowedValues = $this->getEnumStringAllowableValues(); + if (!is_null($this->container['enum_string']) && !in_array($this->container['enum_string'], $allowedValues, true)) { + return false; + } + if ($this->container['enum_string_required'] === null) { + return false; + } + $allowedValues = $this->getEnumStringRequiredAllowableValues(); + if (!is_null($this->container['enum_string_required']) && !in_array($this->container['enum_string_required'], $allowedValues, true)) { + return false; + } + $allowedValues = $this->getEnumIntegerAllowableValues(); + if (!is_null($this->container['enum_integer']) && !in_array($this->container['enum_integer'], $allowedValues, true)) { + return false; + } + $allowedValues = $this->getEnumNumberAllowableValues(); + if (!is_null($this->container['enum_number']) && !in_array($this->container['enum_number'], $allowedValues, true)) { + return false; + } + return true; + } + + + /** + * Gets enum_string + * + * @return string + */ + public function getEnumString() + { + return $this->container['enum_string']; + } + + /** + * Sets enum_string + * + * @param string $enum_string enum_string + * + * @return $this + */ + public function setEnumString($enum_string) + { + $allowedValues = $this->getEnumStringAllowableValues(); + if (!is_null($enum_string) && !in_array($enum_string, $allowedValues, true)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value for 'enum_string', must be one of '%s'", + implode("', '", $allowedValues) + ) + ); + } + $this->container['enum_string'] = $enum_string; + + return $this; + } + + /** + * Gets enum_string_required + * + * @return string + */ + public function getEnumStringRequired() + { + return $this->container['enum_string_required']; + } + + /** + * Sets enum_string_required + * + * @param string $enum_string_required enum_string_required + * + * @return $this + */ + public function setEnumStringRequired($enum_string_required) + { + $allowedValues = $this->getEnumStringRequiredAllowableValues(); + if (!in_array($enum_string_required, $allowedValues, true)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value for 'enum_string_required', must be one of '%s'", + implode("', '", $allowedValues) + ) + ); + } + $this->container['enum_string_required'] = $enum_string_required; + + return $this; + } + + /** + * Gets enum_integer + * + * @return int + */ + public function getEnumInteger() + { + return $this->container['enum_integer']; + } + + /** + * Sets enum_integer + * + * @param int $enum_integer enum_integer + * + * @return $this + */ + public function setEnumInteger($enum_integer) + { + $allowedValues = $this->getEnumIntegerAllowableValues(); + if (!is_null($enum_integer) && !in_array($enum_integer, $allowedValues, true)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value for 'enum_integer', must be one of '%s'", + implode("', '", $allowedValues) + ) + ); + } + $this->container['enum_integer'] = $enum_integer; + + return $this; + } + + /** + * Gets enum_number + * + * @return double + */ + public function getEnumNumber() + { + return $this->container['enum_number']; + } + + /** + * Sets enum_number + * + * @param double $enum_number enum_number + * + * @return $this + */ + public function setEnumNumber($enum_number) + { + $allowedValues = $this->getEnumNumberAllowableValues(); + if (!is_null($enum_number) && !in_array($enum_number, $allowedValues, true)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value for 'enum_number', must be one of '%s'", + implode("', '", $allowedValues) + ) + ); + } + $this->container['enum_number'] = $enum_number; + + return $this; + } + + /** + * Gets outer_enum + * + * @return \Swagger\Client\Model\OuterEnum + */ + public function getOuterEnum() + { + return $this->container['outer_enum']; + } + + /** + * Sets outer_enum + * + * @param \Swagger\Client\Model\OuterEnum $outer_enum outer_enum + * + * @return $this + */ + public function setOuterEnum($outer_enum) + { + $this->container['outer_enum'] = $outer_enum; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php new file mode 100644 index 000000000000..df4fc264a4ab --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -0,0 +1,817 @@ + 'int', + 'int32' => 'int', + 'int64' => 'int', + 'number' => 'float', + 'float' => 'float', + 'double' => 'double', + 'string' => 'string', + 'byte' => 'string', + 'binary' => '\SplFileObject', + 'date' => '\DateTime', + 'date_time' => '\DateTime', + 'uuid' => 'string', + 'password' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'integer' => 'int32', + 'int32' => 'int32', + 'int64' => 'int64', + 'number' => null, + 'float' => 'float', + 'double' => 'double', + 'string' => null, + 'byte' => 'byte', + 'binary' => 'binary', + 'date' => 'date', + 'date_time' => 'date-time', + 'uuid' => 'uuid', + 'password' => 'password' + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'integer' => 'integer', + 'int32' => 'int32', + 'int64' => 'int64', + 'number' => 'number', + 'float' => 'float', + 'double' => 'double', + 'string' => 'string', + 'byte' => 'byte', + 'binary' => 'binary', + 'date' => 'date', + 'date_time' => 'dateTime', + 'uuid' => 'uuid', + 'password' => 'password' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'integer' => 'setInteger', + 'int32' => 'setInt32', + 'int64' => 'setInt64', + 'number' => 'setNumber', + 'float' => 'setFloat', + 'double' => 'setDouble', + 'string' => 'setString', + 'byte' => 'setByte', + 'binary' => 'setBinary', + 'date' => 'setDate', + 'date_time' => 'setDateTime', + 'uuid' => 'setUuid', + 'password' => 'setPassword' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'integer' => 'getInteger', + 'int32' => 'getInt32', + 'int64' => 'getInt64', + 'number' => 'getNumber', + 'float' => 'getFloat', + 'double' => 'getDouble', + 'string' => 'getString', + 'byte' => 'getByte', + 'binary' => 'getBinary', + 'date' => 'getDate', + 'date_time' => 'getDateTime', + 'uuid' => 'getUuid', + 'password' => 'getPassword' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['integer'] = isset($data['integer']) ? $data['integer'] : null; + $this->container['int32'] = isset($data['int32']) ? $data['int32'] : null; + $this->container['int64'] = isset($data['int64']) ? $data['int64'] : null; + $this->container['number'] = isset($data['number']) ? $data['number'] : null; + $this->container['float'] = isset($data['float']) ? $data['float'] : null; + $this->container['double'] = isset($data['double']) ? $data['double'] : null; + $this->container['string'] = isset($data['string']) ? $data['string'] : null; + $this->container['byte'] = isset($data['byte']) ? $data['byte'] : null; + $this->container['binary'] = isset($data['binary']) ? $data['binary'] : null; + $this->container['date'] = isset($data['date']) ? $data['date'] : null; + $this->container['date_time'] = isset($data['date_time']) ? $data['date_time'] : null; + $this->container['uuid'] = isset($data['uuid']) ? $data['uuid'] : null; + $this->container['password'] = isset($data['password']) ? $data['password'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + if (!is_null($this->container['integer']) && ($this->container['integer'] > 100)) { + $invalidProperties[] = "invalid value for 'integer', must be smaller than or equal to 100."; + } + + if (!is_null($this->container['integer']) && ($this->container['integer'] < 10)) { + $invalidProperties[] = "invalid value for 'integer', must be bigger than or equal to 10."; + } + + if (!is_null($this->container['int32']) && ($this->container['int32'] > 200)) { + $invalidProperties[] = "invalid value for 'int32', must be smaller than or equal to 200."; + } + + if (!is_null($this->container['int32']) && ($this->container['int32'] < 20)) { + $invalidProperties[] = "invalid value for 'int32', must be bigger than or equal to 20."; + } + + if ($this->container['number'] === null) { + $invalidProperties[] = "'number' can't be null"; + } + if (($this->container['number'] > 543.2)) { + $invalidProperties[] = "invalid value for 'number', must be smaller than or equal to 543.2."; + } + + if (($this->container['number'] < 32.1)) { + $invalidProperties[] = "invalid value for 'number', must be bigger than or equal to 32.1."; + } + + if (!is_null($this->container['float']) && ($this->container['float'] > 987.6)) { + $invalidProperties[] = "invalid value for 'float', must be smaller than or equal to 987.6."; + } + + if (!is_null($this->container['float']) && ($this->container['float'] < 54.3)) { + $invalidProperties[] = "invalid value for 'float', must be bigger than or equal to 54.3."; + } + + if (!is_null($this->container['double']) && ($this->container['double'] > 123.4)) { + $invalidProperties[] = "invalid value for 'double', must be smaller than or equal to 123.4."; + } + + if (!is_null($this->container['double']) && ($this->container['double'] < 67.8)) { + $invalidProperties[] = "invalid value for 'double', must be bigger than or equal to 67.8."; + } + + if ($this->container['byte'] === null) { + $invalidProperties[] = "'byte' can't be null"; + } + if ($this->container['date'] === null) { + $invalidProperties[] = "'date' can't be null"; + } + if ($this->container['password'] === null) { + $invalidProperties[] = "'password' can't be null"; + } + if ((mb_strlen($this->container['password']) > 64)) { + $invalidProperties[] = "invalid value for 'password', the character length must be smaller than or equal to 64."; + } + + if ((mb_strlen($this->container['password']) < 10)) { + $invalidProperties[] = "invalid value for 'password', the character length must be bigger than or equal to 10."; + } + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + if ($this->container['integer'] > 100) { + return false; + } + if ($this->container['integer'] < 10) { + return false; + } + if ($this->container['int32'] > 200) { + return false; + } + if ($this->container['int32'] < 20) { + return false; + } + if ($this->container['number'] === null) { + return false; + } + if ($this->container['number'] > 543.2) { + return false; + } + if ($this->container['number'] < 32.1) { + return false; + } + if ($this->container['float'] > 987.6) { + return false; + } + if ($this->container['float'] < 54.3) { + return false; + } + if ($this->container['double'] > 123.4) { + return false; + } + if ($this->container['double'] < 67.8) { + return false; + } + if ($this->container['byte'] === null) { + return false; + } + if ($this->container['date'] === null) { + return false; + } + if ($this->container['password'] === null) { + return false; + } + if (mb_strlen($this->container['password']) > 64) { + return false; + } + if (mb_strlen($this->container['password']) < 10) { + return false; + } + return true; + } + + + /** + * Gets integer + * + * @return int + */ + public function getInteger() + { + return $this->container['integer']; + } + + /** + * Sets integer + * + * @param int $integer integer + * + * @return $this + */ + public function setInteger($integer) + { + + if (!is_null($integer) && ($integer > 100)) { + throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be smaller than or equal to 100.'); + } + if (!is_null($integer) && ($integer < 10)) { + throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be bigger than or equal to 10.'); + } + + $this->container['integer'] = $integer; + + return $this; + } + + /** + * Gets int32 + * + * @return int + */ + public function getInt32() + { + return $this->container['int32']; + } + + /** + * Sets int32 + * + * @param int $int32 int32 + * + * @return $this + */ + public function setInt32($int32) + { + + if (!is_null($int32) && ($int32 > 200)) { + throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be smaller than or equal to 200.'); + } + if (!is_null($int32) && ($int32 < 20)) { + throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be bigger than or equal to 20.'); + } + + $this->container['int32'] = $int32; + + return $this; + } + + /** + * Gets int64 + * + * @return int + */ + public function getInt64() + { + return $this->container['int64']; + } + + /** + * Sets int64 + * + * @param int $int64 int64 + * + * @return $this + */ + public function setInt64($int64) + { + $this->container['int64'] = $int64; + + return $this; + } + + /** + * Gets number + * + * @return float + */ + public function getNumber() + { + return $this->container['number']; + } + + /** + * Sets number + * + * @param float $number number + * + * @return $this + */ + public function setNumber($number) + { + + if (($number > 543.2)) { + throw new \InvalidArgumentException('invalid value for $number when calling FormatTest., must be smaller than or equal to 543.2.'); + } + if (($number < 32.1)) { + throw new \InvalidArgumentException('invalid value for $number when calling FormatTest., must be bigger than or equal to 32.1.'); + } + + $this->container['number'] = $number; + + return $this; + } + + /** + * Gets float + * + * @return float + */ + public function getFloat() + { + return $this->container['float']; + } + + /** + * Sets float + * + * @param float $float float + * + * @return $this + */ + public function setFloat($float) + { + + if (!is_null($float) && ($float > 987.6)) { + throw new \InvalidArgumentException('invalid value for $float when calling FormatTest., must be smaller than or equal to 987.6.'); + } + if (!is_null($float) && ($float < 54.3)) { + throw new \InvalidArgumentException('invalid value for $float when calling FormatTest., must be bigger than or equal to 54.3.'); + } + + $this->container['float'] = $float; + + return $this; + } + + /** + * Gets double + * + * @return double + */ + public function getDouble() + { + return $this->container['double']; + } + + /** + * Sets double + * + * @param double $double double + * + * @return $this + */ + public function setDouble($double) + { + + if (!is_null($double) && ($double > 123.4)) { + throw new \InvalidArgumentException('invalid value for $double when calling FormatTest., must be smaller than or equal to 123.4.'); + } + if (!is_null($double) && ($double < 67.8)) { + throw new \InvalidArgumentException('invalid value for $double when calling FormatTest., must be bigger than or equal to 67.8.'); + } + + $this->container['double'] = $double; + + return $this; + } + + /** + * Gets string + * + * @return string + */ + public function getString() + { + return $this->container['string']; + } + + /** + * Sets string + * + * @param string $string string + * + * @return $this + */ + public function setString($string) + { + $this->container['string'] = $string; + + return $this; + } + + /** + * Gets byte + * + * @return string + */ + public function getByte() + { + return $this->container['byte']; + } + + /** + * Sets byte + * + * @param string $byte byte + * + * @return $this + */ + public function setByte($byte) + { + $this->container['byte'] = $byte; + + return $this; + } + + /** + * Gets binary + * + * @return \SplFileObject + */ + public function getBinary() + { + return $this->container['binary']; + } + + /** + * Sets binary + * + * @param \SplFileObject $binary binary + * + * @return $this + */ + public function setBinary($binary) + { + $this->container['binary'] = $binary; + + return $this; + } + + /** + * Gets date + * + * @return \DateTime + */ + public function getDate() + { + return $this->container['date']; + } + + /** + * Sets date + * + * @param \DateTime $date date + * + * @return $this + */ + public function setDate($date) + { + $this->container['date'] = $date; + + return $this; + } + + /** + * Gets date_time + * + * @return \DateTime + */ + public function getDateTime() + { + return $this->container['date_time']; + } + + /** + * Sets date_time + * + * @param \DateTime $date_time date_time + * + * @return $this + */ + public function setDateTime($date_time) + { + $this->container['date_time'] = $date_time; + + return $this; + } + + /** + * Gets uuid + * + * @return string + */ + public function getUuid() + { + return $this->container['uuid']; + } + + /** + * Sets uuid + * + * @param string $uuid uuid + * + * @return $this + */ + public function setUuid($uuid) + { + $this->container['uuid'] = $uuid; + + return $this; + } + + /** + * Gets password + * + * @return string + */ + public function getPassword() + { + return $this->container['password']; + } + + /** + * Sets password + * + * @param string $password password + * + * @return $this + */ + public function setPassword($password) + { + if ((mb_strlen($password) > 64)) { + throw new \InvalidArgumentException('invalid length for $password when calling FormatTest., must be smaller than or equal to 64.'); + } + if ((mb_strlen($password) < 10)) { + throw new \InvalidArgumentException('invalid length for $password when calling FormatTest., must be bigger than or equal to 10.'); + } + + $this->container['password'] = $password; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php new file mode 100644 index 000000000000..db25cac8084d --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php @@ -0,0 +1,332 @@ + 'string', + 'foo' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'bar' => null, + 'foo' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'bar' => 'bar', + 'foo' => 'foo' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'bar' => 'setBar', + 'foo' => 'setFoo' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'bar' => 'getBar', + 'foo' => 'getFoo' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['bar'] = isset($data['bar']) ? $data['bar'] : null; + $this->container['foo'] = isset($data['foo']) ? $data['foo'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets bar + * + * @return string + */ + public function getBar() + { + return $this->container['bar']; + } + + /** + * Sets bar + * + * @param string $bar bar + * + * @return $this + */ + public function setBar($bar) + { + $this->container['bar'] = $bar; + + return $this; + } + + /** + * Gets foo + * + * @return string + */ + public function getFoo() + { + return $this->container['foo']; + } + + /** + * Sets foo + * + * @param string $foo foo + * + * @return $this + */ + public function setFoo($foo) + { + $this->container['foo'] = $foo; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php new file mode 100644 index 000000000000..d96af580b0db --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php @@ -0,0 +1,356 @@ + 'map[string,map[string,string]]', + 'map_of_enum_string' => 'map[string,string]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'map_map_of_string' => null, + 'map_of_enum_string' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'map_map_of_string' => 'map_map_of_string', + 'map_of_enum_string' => 'map_of_enum_string' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'map_map_of_string' => 'setMapMapOfString', + 'map_of_enum_string' => 'setMapOfEnumString' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'map_map_of_string' => 'getMapMapOfString', + 'map_of_enum_string' => 'getMapOfEnumString' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + const MAP_OF_ENUM_STRING_UPPER = 'UPPER'; + const MAP_OF_ENUM_STRING_LOWER = 'lower'; + + + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getMapOfEnumStringAllowableValues() + { + return [ + self::MAP_OF_ENUM_STRING_UPPER, + self::MAP_OF_ENUM_STRING_LOWER, + ]; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['map_map_of_string'] = isset($data['map_map_of_string']) ? $data['map_map_of_string'] : null; + $this->container['map_of_enum_string'] = isset($data['map_of_enum_string']) ? $data['map_of_enum_string'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets map_map_of_string + * + * @return map[string,map[string,string]] + */ + public function getMapMapOfString() + { + return $this->container['map_map_of_string']; + } + + /** + * Sets map_map_of_string + * + * @param map[string,map[string,string]] $map_map_of_string map_map_of_string + * + * @return $this + */ + public function setMapMapOfString($map_map_of_string) + { + $this->container['map_map_of_string'] = $map_map_of_string; + + return $this; + } + + /** + * Gets map_of_enum_string + * + * @return map[string,string] + */ + public function getMapOfEnumString() + { + return $this->container['map_of_enum_string']; + } + + /** + * Sets map_of_enum_string + * + * @param map[string,string] $map_of_enum_string map_of_enum_string + * + * @return $this + */ + public function setMapOfEnumString($map_of_enum_string) + { + $allowedValues = $this->getMapOfEnumStringAllowableValues(); + if (!is_null($map_of_enum_string) && array_diff($map_of_enum_string, $allowedValues)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value for 'map_of_enum_string', must be one of '%s'", + implode("', '", $allowedValues) + ) + ); + } + $this->container['map_of_enum_string'] = $map_of_enum_string; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php new file mode 100644 index 000000000000..fac70fa65e7f --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -0,0 +1,362 @@ + 'string', + 'date_time' => '\DateTime', + 'map' => 'map[string,\Swagger\Client\Model\Animal]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'uuid' => 'uuid', + 'date_time' => 'date-time', + 'map' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'uuid' => 'uuid', + 'date_time' => 'dateTime', + 'map' => 'map' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'uuid' => 'setUuid', + 'date_time' => 'setDateTime', + 'map' => 'setMap' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'uuid' => 'getUuid', + 'date_time' => 'getDateTime', + 'map' => 'getMap' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['uuid'] = isset($data['uuid']) ? $data['uuid'] : null; + $this->container['date_time'] = isset($data['date_time']) ? $data['date_time'] : null; + $this->container['map'] = isset($data['map']) ? $data['map'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets uuid + * + * @return string + */ + public function getUuid() + { + return $this->container['uuid']; + } + + /** + * Sets uuid + * + * @param string $uuid uuid + * + * @return $this + */ + public function setUuid($uuid) + { + $this->container['uuid'] = $uuid; + + return $this; + } + + /** + * Gets date_time + * + * @return \DateTime + */ + public function getDateTime() + { + return $this->container['date_time']; + } + + /** + * Sets date_time + * + * @param \DateTime $date_time date_time + * + * @return $this + */ + public function setDateTime($date_time) + { + $this->container['date_time'] = $date_time; + + return $this; + } + + /** + * Gets map + * + * @return map[string,\Swagger\Client\Model\Animal] + */ + public function getMap() + { + return $this->container['map']; + } + + /** + * Sets map + * + * @param map[string,\Swagger\Client\Model\Animal] $map map + * + * @return $this + */ + public function setMap($map) + { + $this->container['map'] = $map; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php new file mode 100644 index 000000000000..f0d46fd5ee5c --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -0,0 +1,333 @@ + 'int', + 'class' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'name' => 'int32', + 'class' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'name' => 'name', + 'class' => 'class' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'name' => 'setName', + 'class' => 'setClass' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'name' => 'getName', + 'class' => 'getClass' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['name'] = isset($data['name']) ? $data['name'] : null; + $this->container['class'] = isset($data['class']) ? $data['class'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets name + * + * @return int + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param int $name name + * + * @return $this + */ + public function setName($name) + { + $this->container['name'] = $name; + + return $this; + } + + /** + * Gets class + * + * @return string + */ + public function getClass() + { + return $this->container['class']; + } + + /** + * Sets class + * + * @param string $class class + * + * @return $this + */ + public function setClass($class) + { + $this->container['class'] = $class; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ModelInterface.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ModelInterface.php new file mode 100644 index 000000000000..18fcdeafbe9b --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ModelInterface.php @@ -0,0 +1,96 @@ + 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + '_123_list' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + '_123_list' => '123-list' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + '_123_list' => 'set123List' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + '_123_list' => 'get123List' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['_123_list'] = isset($data['_123_list']) ? $data['_123_list'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets _123_list + * + * @return string + */ + public function get123List() + { + return $this->container['_123_list']; + } + + /** + * Sets _123_list + * + * @param string $_123_list _123_list + * + * @return $this + */ + public function set123List($_123_list) + { + $this->container['_123_list'] = $_123_list; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php new file mode 100644 index 000000000000..2f9e91bf7a58 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -0,0 +1,303 @@ + 'int' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'return' => 'int32' + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'return' => 'return' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'return' => 'setReturn' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'return' => 'getReturn' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['return'] = isset($data['return']) ? $data['return'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets return + * + * @return int + */ + public function getReturn() + { + return $this->container['return']; + } + + /** + * Sets return + * + * @param int $return return + * + * @return $this + */ + public function setReturn($return) + { + $this->container['return'] = $return; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Name.php new file mode 100644 index 000000000000..6190a85ab057 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -0,0 +1,399 @@ + 'int', + 'snake_case' => 'int', + 'property' => 'string', + '_123_number' => 'int' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'name' => 'int32', + 'snake_case' => 'int32', + 'property' => null, + '_123_number' => 'int32' + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'name' => 'name', + 'snake_case' => 'snake_case', + 'property' => 'property', + '_123_number' => '123Number' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'name' => 'setName', + 'snake_case' => 'setSnakeCase', + 'property' => 'setProperty', + '_123_number' => 'set123Number' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'name' => 'getName', + 'snake_case' => 'getSnakeCase', + 'property' => 'getProperty', + '_123_number' => 'get123Number' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['name'] = isset($data['name']) ? $data['name'] : null; + $this->container['snake_case'] = isset($data['snake_case']) ? $data['snake_case'] : null; + $this->container['property'] = isset($data['property']) ? $data['property'] : null; + $this->container['_123_number'] = isset($data['_123_number']) ? $data['_123_number'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + if ($this->container['name'] === null) { + $invalidProperties[] = "'name' can't be null"; + } + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + if ($this->container['name'] === null) { + return false; + } + return true; + } + + + /** + * Gets name + * + * @return int + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param int $name name + * + * @return $this + */ + public function setName($name) + { + $this->container['name'] = $name; + + return $this; + } + + /** + * Gets snake_case + * + * @return int + */ + public function getSnakeCase() + { + return $this->container['snake_case']; + } + + /** + * Sets snake_case + * + * @param int $snake_case snake_case + * + * @return $this + */ + public function setSnakeCase($snake_case) + { + $this->container['snake_case'] = $snake_case; + + return $this; + } + + /** + * Gets property + * + * @return string + */ + public function getProperty() + { + return $this->container['property']; + } + + /** + * Sets property + * + * @param string $property property + * + * @return $this + */ + public function setProperty($property) + { + $this->container['property'] = $property; + + return $this; + } + + /** + * Gets _123_number + * + * @return int + */ + public function get123Number() + { + return $this->container['_123_number']; + } + + /** + * Sets _123_number + * + * @param int $_123_number _123_number + * + * @return $this + */ + public function set123Number($_123_number) + { + $this->container['_123_number'] = $_123_number; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php new file mode 100644 index 000000000000..cd2ae8517d29 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php @@ -0,0 +1,302 @@ + 'float' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'just_number' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'just_number' => 'JustNumber' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'just_number' => 'setJustNumber' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'just_number' => 'getJustNumber' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['just_number'] = isset($data['just_number']) ? $data['just_number'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets just_number + * + * @return float + */ + public function getJustNumber() + { + return $this->container['just_number']; + } + + /** + * Sets just_number + * + * @param float $just_number just_number + * + * @return $this + */ + public function setJustNumber($just_number) + { + $this->container['just_number'] = $just_number; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Order.php new file mode 100644 index 000000000000..a5dfe109abb2 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -0,0 +1,490 @@ + 'int', + 'pet_id' => 'int', + 'quantity' => 'int', + 'ship_date' => '\DateTime', + 'status' => 'string', + 'complete' => 'bool' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'id' => 'int64', + 'pet_id' => 'int64', + 'quantity' => 'int32', + 'ship_date' => 'date-time', + 'status' => null, + 'complete' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'id' => 'id', + 'pet_id' => 'petId', + 'quantity' => 'quantity', + 'ship_date' => 'shipDate', + 'status' => 'status', + 'complete' => 'complete' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'id' => 'setId', + 'pet_id' => 'setPetId', + 'quantity' => 'setQuantity', + 'ship_date' => 'setShipDate', + 'status' => 'setStatus', + 'complete' => 'setComplete' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'id' => 'getId', + 'pet_id' => 'getPetId', + 'quantity' => 'getQuantity', + 'ship_date' => 'getShipDate', + 'status' => 'getStatus', + 'complete' => 'getComplete' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + const STATUS_PLACED = 'placed'; + const STATUS_APPROVED = 'approved'; + const STATUS_DELIVERED = 'delivered'; + + + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getStatusAllowableValues() + { + return [ + self::STATUS_PLACED, + self::STATUS_APPROVED, + self::STATUS_DELIVERED, + ]; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['pet_id'] = isset($data['pet_id']) ? $data['pet_id'] : null; + $this->container['quantity'] = isset($data['quantity']) ? $data['quantity'] : null; + $this->container['ship_date'] = isset($data['ship_date']) ? $data['ship_date'] : null; + $this->container['status'] = isset($data['status']) ? $data['status'] : null; + $this->container['complete'] = isset($data['complete']) ? $data['complete'] : false; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + $allowedValues = $this->getStatusAllowableValues(); + if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { + $invalidProperties[] = sprintf( + "invalid value for 'status', must be one of '%s'", + implode("', '", $allowedValues) + ); + } + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + $allowedValues = $this->getStatusAllowableValues(); + if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { + return false; + } + return true; + } + + + /** + * Gets id + * + * @return int + */ + public function getId() + { + return $this->container['id']; + } + + /** + * Sets id + * + * @param int $id id + * + * @return $this + */ + public function setId($id) + { + $this->container['id'] = $id; + + return $this; + } + + /** + * Gets pet_id + * + * @return int + */ + public function getPetId() + { + return $this->container['pet_id']; + } + + /** + * Sets pet_id + * + * @param int $pet_id pet_id + * + * @return $this + */ + public function setPetId($pet_id) + { + $this->container['pet_id'] = $pet_id; + + return $this; + } + + /** + * Gets quantity + * + * @return int + */ + public function getQuantity() + { + return $this->container['quantity']; + } + + /** + * Sets quantity + * + * @param int $quantity quantity + * + * @return $this + */ + public function setQuantity($quantity) + { + $this->container['quantity'] = $quantity; + + return $this; + } + + /** + * Gets ship_date + * + * @return \DateTime + */ + public function getShipDate() + { + return $this->container['ship_date']; + } + + /** + * Sets ship_date + * + * @param \DateTime $ship_date ship_date + * + * @return $this + */ + public function setShipDate($ship_date) + { + $this->container['ship_date'] = $ship_date; + + return $this; + } + + /** + * Gets status + * + * @return string + */ + public function getStatus() + { + return $this->container['status']; + } + + /** + * Sets status + * + * @param string $status Order Status + * + * @return $this + */ + public function setStatus($status) + { + $allowedValues = $this->getStatusAllowableValues(); + if (!is_null($status) && !in_array($status, $allowedValues, true)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value for 'status', must be one of '%s'", + implode("', '", $allowedValues) + ) + ); + } + $this->container['status'] = $status; + + return $this; + } + + /** + * Gets complete + * + * @return bool + */ + public function getComplete() + { + return $this->container['complete']; + } + + /** + * Sets complete + * + * @param bool $complete complete + * + * @return $this + */ + public function setComplete($complete) + { + $this->container['complete'] = $complete; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterBoolean.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterBoolean.php new file mode 100644 index 000000000000..06bd24f8714b --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterBoolean.php @@ -0,0 +1,277 @@ +container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterComposite.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterComposite.php new file mode 100644 index 000000000000..61a5143b9ede --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterComposite.php @@ -0,0 +1,362 @@ + '\Swagger\Client\Model\OuterNumber', + 'my_string' => '\Swagger\Client\Model\OuterString', + 'my_boolean' => '\Swagger\Client\Model\OuterBoolean' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'my_number' => null, + 'my_string' => null, + 'my_boolean' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'my_number' => 'my_number', + 'my_string' => 'my_string', + 'my_boolean' => 'my_boolean' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'my_number' => 'setMyNumber', + 'my_string' => 'setMyString', + 'my_boolean' => 'setMyBoolean' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'my_number' => 'getMyNumber', + 'my_string' => 'getMyString', + 'my_boolean' => 'getMyBoolean' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['my_number'] = isset($data['my_number']) ? $data['my_number'] : null; + $this->container['my_string'] = isset($data['my_string']) ? $data['my_string'] : null; + $this->container['my_boolean'] = isset($data['my_boolean']) ? $data['my_boolean'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets my_number + * + * @return \Swagger\Client\Model\OuterNumber + */ + public function getMyNumber() + { + return $this->container['my_number']; + } + + /** + * Sets my_number + * + * @param \Swagger\Client\Model\OuterNumber $my_number my_number + * + * @return $this + */ + public function setMyNumber($my_number) + { + $this->container['my_number'] = $my_number; + + return $this; + } + + /** + * Gets my_string + * + * @return \Swagger\Client\Model\OuterString + */ + public function getMyString() + { + return $this->container['my_string']; + } + + /** + * Sets my_string + * + * @param \Swagger\Client\Model\OuterString $my_string my_string + * + * @return $this + */ + public function setMyString($my_string) + { + $this->container['my_string'] = $my_string; + + return $this; + } + + /** + * Gets my_boolean + * + * @return \Swagger\Client\Model\OuterBoolean + */ + public function getMyBoolean() + { + return $this->container['my_boolean']; + } + + /** + * Sets my_boolean + * + * @param \Swagger\Client\Model\OuterBoolean $my_boolean my_boolean + * + * @return $this + */ + public function setMyBoolean($my_boolean) + { + $this->container['my_boolean'] = $my_boolean; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterEnum.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterEnum.php new file mode 100644 index 000000000000..fa8d60be809b --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterEnum.php @@ -0,0 +1,64 @@ +container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterString.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterString.php new file mode 100644 index 000000000000..0efbc88867e7 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/OuterString.php @@ -0,0 +1,277 @@ +container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php new file mode 100644 index 000000000000..3ad44bb06051 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -0,0 +1,502 @@ + 'int', + 'category' => '\Swagger\Client\Model\Category', + 'name' => 'string', + 'photo_urls' => 'string[]', + 'tags' => '\Swagger\Client\Model\Tag[]', + 'status' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'id' => 'int64', + 'category' => null, + 'name' => null, + 'photo_urls' => null, + 'tags' => null, + 'status' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'id' => 'id', + 'category' => 'category', + 'name' => 'name', + 'photo_urls' => 'photoUrls', + 'tags' => 'tags', + 'status' => 'status' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'id' => 'setId', + 'category' => 'setCategory', + 'name' => 'setName', + 'photo_urls' => 'setPhotoUrls', + 'tags' => 'setTags', + 'status' => 'setStatus' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'id' => 'getId', + 'category' => 'getCategory', + 'name' => 'getName', + 'photo_urls' => 'getPhotoUrls', + 'tags' => 'getTags', + 'status' => 'getStatus' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + const STATUS_AVAILABLE = 'available'; + const STATUS_PENDING = 'pending'; + const STATUS_SOLD = 'sold'; + + + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getStatusAllowableValues() + { + return [ + self::STATUS_AVAILABLE, + self::STATUS_PENDING, + self::STATUS_SOLD, + ]; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['category'] = isset($data['category']) ? $data['category'] : null; + $this->container['name'] = isset($data['name']) ? $data['name'] : null; + $this->container['photo_urls'] = isset($data['photo_urls']) ? $data['photo_urls'] : null; + $this->container['tags'] = isset($data['tags']) ? $data['tags'] : null; + $this->container['status'] = isset($data['status']) ? $data['status'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + if ($this->container['name'] === null) { + $invalidProperties[] = "'name' can't be null"; + } + if ($this->container['photo_urls'] === null) { + $invalidProperties[] = "'photo_urls' can't be null"; + } + $allowedValues = $this->getStatusAllowableValues(); + if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { + $invalidProperties[] = sprintf( + "invalid value for 'status', must be one of '%s'", + implode("', '", $allowedValues) + ); + } + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + if ($this->container['name'] === null) { + return false; + } + if ($this->container['photo_urls'] === null) { + return false; + } + $allowedValues = $this->getStatusAllowableValues(); + if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { + return false; + } + return true; + } + + + /** + * Gets id + * + * @return int + */ + public function getId() + { + return $this->container['id']; + } + + /** + * Sets id + * + * @param int $id id + * + * @return $this + */ + public function setId($id) + { + $this->container['id'] = $id; + + return $this; + } + + /** + * Gets category + * + * @return \Swagger\Client\Model\Category + */ + public function getCategory() + { + return $this->container['category']; + } + + /** + * Sets category + * + * @param \Swagger\Client\Model\Category $category category + * + * @return $this + */ + public function setCategory($category) + { + $this->container['category'] = $category; + + return $this; + } + + /** + * Gets name + * + * @return string + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param string $name name + * + * @return $this + */ + public function setName($name) + { + $this->container['name'] = $name; + + return $this; + } + + /** + * Gets photo_urls + * + * @return string[] + */ + public function getPhotoUrls() + { + return $this->container['photo_urls']; + } + + /** + * Sets photo_urls + * + * @param string[] $photo_urls photo_urls + * + * @return $this + */ + public function setPhotoUrls($photo_urls) + { + $this->container['photo_urls'] = $photo_urls; + + return $this; + } + + /** + * Gets tags + * + * @return \Swagger\Client\Model\Tag[] + */ + public function getTags() + { + return $this->container['tags']; + } + + /** + * Sets tags + * + * @param \Swagger\Client\Model\Tag[] $tags tags + * + * @return $this + */ + public function setTags($tags) + { + $this->container['tags'] = $tags; + + return $this; + } + + /** + * Gets status + * + * @return string + */ + public function getStatus() + { + return $this->container['status']; + } + + /** + * Sets status + * + * @param string $status pet status in the store + * + * @return $this + */ + public function setStatus($status) + { + $allowedValues = $this->getStatusAllowableValues(); + if (!is_null($status) && !in_array($status, $allowedValues, true)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value for 'status', must be one of '%s'", + implode("', '", $allowedValues) + ) + ); + } + $this->container['status'] = $status; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php new file mode 100644 index 000000000000..c7eb5cb33392 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php @@ -0,0 +1,332 @@ + 'string', + 'baz' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'bar' => null, + 'baz' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'bar' => 'bar', + 'baz' => 'baz' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'bar' => 'setBar', + 'baz' => 'setBaz' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'bar' => 'getBar', + 'baz' => 'getBaz' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['bar'] = isset($data['bar']) ? $data['bar'] : null; + $this->container['baz'] = isset($data['baz']) ? $data['baz'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets bar + * + * @return string + */ + public function getBar() + { + return $this->container['bar']; + } + + /** + * Sets bar + * + * @param string $bar bar + * + * @return $this + */ + public function setBar($bar) + { + $this->container['bar'] = $bar; + + return $this; + } + + /** + * Gets baz + * + * @return string + */ + public function getBaz() + { + return $this->container['baz']; + } + + /** + * Sets baz + * + * @param string $baz baz + * + * @return $this + */ + public function setBaz($baz) + { + $this->container['baz'] = $baz; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName_.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName_.php new file mode 100644 index 000000000000..251df3199878 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName_.php @@ -0,0 +1,302 @@ + 'int' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'special_property_name' => 'int64' + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'special_property_name' => '$special[property.name]' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'special_property_name' => 'setSpecialPropertyName' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'special_property_name' => 'getSpecialPropertyName' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['special_property_name'] = isset($data['special_property_name']) ? $data['special_property_name'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets special_property_name + * + * @return int + */ + public function getSpecialPropertyName() + { + return $this->container['special_property_name']; + } + + /** + * Sets special_property_name + * + * @param int $special_property_name special_property_name + * + * @return $this + */ + public function setSpecialPropertyName($special_property_name) + { + $this->container['special_property_name'] = $special_property_name; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php new file mode 100644 index 000000000000..bf9b63dfaed0 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -0,0 +1,332 @@ + 'int', + 'name' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'id' => 'int64', + 'name' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'id' => 'id', + 'name' => 'name' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'id' => 'setId', + 'name' => 'setName' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'id' => 'getId', + 'name' => 'getName' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['name'] = isset($data['name']) ? $data['name'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets id + * + * @return int + */ + public function getId() + { + return $this->container['id']; + } + + /** + * Sets id + * + * @param int $id id + * + * @return $this + */ + public function setId($id) + { + $this->container['id'] = $id; + + return $this; + } + + /** + * Gets name + * + * @return string + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param string $name name + * + * @return $this + */ + public function setName($name) + { + $this->container['name'] = $name; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/User.php new file mode 100644 index 000000000000..0cfe061e7a62 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -0,0 +1,512 @@ + 'int', + 'username' => 'string', + 'first_name' => 'string', + 'last_name' => 'string', + 'email' => 'string', + 'password' => 'string', + 'phone' => 'string', + 'user_status' => 'int' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'id' => 'int64', + 'username' => null, + 'first_name' => null, + 'last_name' => null, + 'email' => null, + 'password' => null, + 'phone' => null, + 'user_status' => 'int32' + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'id' => 'id', + 'username' => 'username', + 'first_name' => 'firstName', + 'last_name' => 'lastName', + 'email' => 'email', + 'password' => 'password', + 'phone' => 'phone', + 'user_status' => 'userStatus' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'id' => 'setId', + 'username' => 'setUsername', + 'first_name' => 'setFirstName', + 'last_name' => 'setLastName', + 'email' => 'setEmail', + 'password' => 'setPassword', + 'phone' => 'setPhone', + 'user_status' => 'setUserStatus' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'id' => 'getId', + 'username' => 'getUsername', + 'first_name' => 'getFirstName', + 'last_name' => 'getLastName', + 'email' => 'getEmail', + 'password' => 'getPassword', + 'phone' => 'getPhone', + 'user_status' => 'getUserStatus' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['username'] = isset($data['username']) ? $data['username'] : null; + $this->container['first_name'] = isset($data['first_name']) ? $data['first_name'] : null; + $this->container['last_name'] = isset($data['last_name']) ? $data['last_name'] : null; + $this->container['email'] = isset($data['email']) ? $data['email'] : null; + $this->container['password'] = isset($data['password']) ? $data['password'] : null; + $this->container['phone'] = isset($data['phone']) ? $data['phone'] : null; + $this->container['user_status'] = isset($data['user_status']) ? $data['user_status'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets id + * + * @return int + */ + public function getId() + { + return $this->container['id']; + } + + /** + * Sets id + * + * @param int $id id + * + * @return $this + */ + public function setId($id) + { + $this->container['id'] = $id; + + return $this; + } + + /** + * Gets username + * + * @return string + */ + public function getUsername() + { + return $this->container['username']; + } + + /** + * Sets username + * + * @param string $username username + * + * @return $this + */ + public function setUsername($username) + { + $this->container['username'] = $username; + + return $this; + } + + /** + * Gets first_name + * + * @return string + */ + public function getFirstName() + { + return $this->container['first_name']; + } + + /** + * Sets first_name + * + * @param string $first_name first_name + * + * @return $this + */ + public function setFirstName($first_name) + { + $this->container['first_name'] = $first_name; + + return $this; + } + + /** + * Gets last_name + * + * @return string + */ + public function getLastName() + { + return $this->container['last_name']; + } + + /** + * Sets last_name + * + * @param string $last_name last_name + * + * @return $this + */ + public function setLastName($last_name) + { + $this->container['last_name'] = $last_name; + + return $this; + } + + /** + * Gets email + * + * @return string + */ + public function getEmail() + { + return $this->container['email']; + } + + /** + * Sets email + * + * @param string $email email + * + * @return $this + */ + public function setEmail($email) + { + $this->container['email'] = $email; + + return $this; + } + + /** + * Gets password + * + * @return string + */ + public function getPassword() + { + return $this->container['password']; + } + + /** + * Sets password + * + * @param string $password password + * + * @return $this + */ + public function setPassword($password) + { + $this->container['password'] = $password; + + return $this; + } + + /** + * Gets phone + * + * @return string + */ + public function getPhone() + { + return $this->container['phone']; + } + + /** + * Sets phone + * + * @param string $phone phone + * + * @return $this + */ + public function setPhone($phone) + { + $this->container['phone'] = $phone; + + return $this; + } + + /** + * Gets user_status + * + * @return int + */ + public function getUserStatus() + { + return $this->container['user_status']; + } + + /** + * Sets user_status + * + * @param int $user_status User Status + * + * @return $this + */ + public function setUserStatus($user_status) + { + $this->container['user_status'] = $user_status; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php new file mode 100644 index 000000000000..cbc97d37d7a7 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -0,0 +1,317 @@ +format('Y-m-d') : $data->format(\DateTime::ATOM); + } elseif (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = self::sanitizeForSerialization($value); + } + return $data; + } elseif (is_object($data)) { + $values = []; + $formats = $data::swaggerFormats(); + foreach ($data::swaggerTypes() as $property => $swaggerType) { + $getter = $data::getters()[$property]; + $value = $data->$getter(); + if ($value !== null + && !in_array($swaggerType, ['DateTime', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true) + && method_exists($swaggerType, 'getAllowableEnumValues') + && !in_array($value, $swaggerType::getAllowableEnumValues())) { + $imploded = implode("', '", $swaggerType::getAllowableEnumValues()); + throw new \InvalidArgumentException("Invalid value for enum '$swaggerType', must be one of: '$imploded'"); + } + if ($value !== null) { + $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value, $swaggerType, $formats[$property]); + } + } + return (object)$values; + } else { + return (string)$data; + } + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param string $filename filename to be sanitized + * + * @return string the sanitized filename + */ + public static function sanitizeFilename($filename) + { + if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { + return $match[1]; + } else { + return $filename; + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * + * @param string $value a string which will be part of the path + * + * @return string the serialized object + */ + public static function toPathValue($value) + { + return rawurlencode(self::toString($value)); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the query, by imploding comma-separated if it's an object. + * If it's a string, pass through unchanged. It will be url-encoded + * later. + * + * @param string[]|string|\DateTime $object an object to be serialized to a string + * + * @return string the serialized object + */ + public static function toQueryValue($object) + { + if (is_array($object)) { + return implode(',', $object); + } else { + return self::toString($object); + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the header. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * + * @param string $value a string which will be part of the header + * + * @return string the header string + */ + public static function toHeaderValue($value) + { + return self::toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the http body (form parameter). If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * + * @param string|\SplFileObject $value the value of the form parameter + * + * @return string the form string + */ + public static function toFormValue($value) + { + if ($value instanceof \SplFileObject) { + return $value->getRealPath(); + } else { + return self::toString($value); + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the parameter. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * + * @param string|\DateTime $value the value of the parameter + * + * @return string the header string + */ + public static function toString($value) + { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(\DateTime::ATOM); + } else { + return $value; + } + } + + /** + * Serialize an array to a string. + * + * @param array $collection collection to serialize to a string + * @param string $collectionFormat the format use for serialization (csv, + * ssv, tsv, pipes, multi) + * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array + * + * @return string + */ + public static function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) + { + if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) { + // http_build_query() almost does the job for us. We just + // need to fix the result of multidimensional arrays. + return preg_replace('/%5B[0-9]+%5D=/', '=', http_build_query($collection, '', '&')); + } + switch ($collectionFormat) { + case 'pipes': + return implode('|', $collection); + + case 'tsv': + return implode("\t", $collection); + + case 'ssv': + return implode(' ', $collection); + + case 'csv': + // Deliberate fall through. CSV is default format. + default: + return implode(',', $collection); + } + } + + /** + * Deserialize a JSON string into an object + * + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string[] $httpHeaders HTTP headers + * @param string $discriminator discriminator if polymorphism is used + * + * @return object|array|null an single or an array of $class instances + */ + public static function deserialize($data, $class, $httpHeaders = null) + { + if (null === $data) { + return null; + } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] + $inner = substr($class, 4, -1); + $deserialized = []; + if (strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $deserialized[$key] = self::deserialize($value, $subClass, null); + } + } + return $deserialized; + } elseif (strcasecmp(substr($class, -2), '[]') === 0) { + $subClass = substr($class, 0, -2); + $values = []; + foreach ($data as $key => $value) { + $values[] = self::deserialize($value, $subClass, null); + } + return $values; + } elseif ($class === 'object') { + settype($data, 'array'); + return $data; + } elseif ($class === '\DateTime') { + // Some API's return an invalid, empty string as a + // date-time property. DateTime::__construct() will return + // the current time for empty input which is probably not + // what is meant. The invalid empty string is probably to + // be interpreted as a missing field/value. Let's handle + // this graceful. + if (!empty($data)) { + return new \DateTime($data); + } else { + return null; + } + } elseif (in_array($class, ['DateTime', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { + settype($data, $class); + return $data; + } elseif ($class === '\SplFileObject') { + /** @var \Psr\Http\Message\StreamInterface $data */ + + // determine file name + if (array_key_exists('Content-Disposition', $httpHeaders) && + preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . DIRECTORY_SEPARATOR . self::sanitizeFilename($match[1]); + } else { + $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); + } + + $file = fopen($filename, 'w'); + while ($chunk = $data->read(200)) { + fwrite($file, $chunk); + } + fclose($file); + + return new \SplFileObject($filename, 'r'); + } elseif (method_exists($class, 'getAllowableEnumValues')) { + if (!in_array($data, $class::getAllowableEnumValues())) { + $imploded = implode("', '", $class::getAllowableEnumValues()); + throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'"); + } + return $data; + } else { + // If a discriminator is defined and points to a valid subclass, use it. + $discriminator = $class::DISCRIMINATOR; + if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { + $subclass = '\Swagger\Client\Model\\' . $data->{$discriminator}; + if (is_subclass_of($subclass, $class)) { + $class = $subclass; + } + } + $instance = new $class(); + foreach ($instance::swaggerTypes() as $property => $type) { + $propertySetter = $instance::setters()[$property]; + + if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) { + continue; + } + + $propertyValue = $data->{$instance::attributeMap()[$property]}; + if (isset($propertyValue)) { + $instance->$propertySetter(self::deserialize($propertyValue, $type, null)); + } + } + return $instance; + } + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/phpunit.xml.dist b/samples/openapi3/client/petstore/php/SwaggerClient-php/phpunit.xml.dist new file mode 100644 index 000000000000..c12ee1484773 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/phpunit.xml.dist @@ -0,0 +1,21 @@ + + + + + ./test/Api + ./test/Model + + + + + + ./lib/Api + ./lib/Model + + + diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/test/Api/AnotherFakeApiTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/test/Api/AnotherFakeApiTest.php new file mode 100644 index 000000000000..f07a9b07b6de --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/test/Api/AnotherFakeApiTest.php @@ -0,0 +1,83 @@ +api = new Api\PetApi(); + + $this->petId = 10005; + $pet = new Model\Pet; + $pet->setId($this->petId); + $pet->setName("PHP Unit Test"); + $pet->setPhotoUrls(array("http://test_php_unit_test.com")); + // new tag + $tag= new Model\Tag; + $tag->setId($this->petId); // use the same id as pet + $tag->setName("test php tag"); + // new category + $category = new Model\Category; + $category->setId($this->petId); // use the same id as pet + $category->setName("test php category"); + + $pet->setTags(array($tag)); + $pet->setCategory($category); + + $pet_api = new Api\PetApi(); + // add a new pet (model) + $add_response = $pet_api->addPet($pet); + } + + public function testAsyncRequest() + { + $promise = $this->api->getPetByIdAsync(10005); + + $promise2 = $this->api->getPetByIdAsync(10005); + + $pet = $promise->wait(); + $pet2 = $promise2->wait(); + $this->assertInstanceOf(Pet::class, $pet); + $this->assertInstanceOf(Pet::class, $pet2); + } + + public function testAsyncRequestWithHttpInfo() + { + $promise = $this->api->getPetByIdAsyncWithHttpInfo($this->petId); + + list($pet, $status, $headers) = $promise->wait(); + $this->assertEquals(200, $status); + $this->assertInternalType('array', $headers); + $this->assertInstanceOf(Pet::class, $pet); + } + + public function testAsyncThrowingException() + { + $this->setExpectedException(ApiException::class); + + $promise = $this->api->getPetByIdAsync(0); + $promise->wait(); + } + + public function testAsyncApiExceptionWithoutWaitIsNotThrown() + { + $promise = $this->api->getPetByIdAsync(0); + sleep(1); + } + + public function testAsyncHttpInfoThrowingException() + { + $this->setExpectedException(ApiException::class); + + $promise = $this->api->getPetByIdAsyncWithHttpInfo(0); + $promise->wait(); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/AuthTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/AuthTest.php new file mode 100644 index 000000000000..d0204352558c --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/AuthTest.php @@ -0,0 +1,62 @@ +setApiKey('api_key', '123qwe'); + + $fakeHttpClient = new FakeHttpClient(); + $api = new PetApi($fakeHttpClient, $authConfig); + $api->getPetById(123); + + $headers = $fakeHttpClient->getLastRequest()->getHeaders(); + + $this->assertArrayHasKey('api_key', $headers); + $this->assertEquals(['123qwe'], $headers['api_key']); + } + + public function testApiToken() + { + $authConfig = new Configuration(); + $authConfig->setAccessToken('asd123'); + + $fakeHttpClient = new FakeHttpClient(); + $api = new PetApi($fakeHttpClient, $authConfig); + $api->addPet(new Pet()); + + $headers = $fakeHttpClient->getLastRequest()->getHeaders(); + + $this->assertArrayHasKey('Authorization', $headers); + $this->assertEquals(['Bearer asd123'], $headers['Authorization']); + } + + public function testBasicAuth() + { + $username = 'user'; + $password = 'password'; + + $authConfig = new Configuration(); + $authConfig->setUsername($username); + $authConfig->setPassword($password); + + $fakeHttpClient = new FakeHttpClient(); + $api = new FakeApi($fakeHttpClient, $authConfig); + $api->testEndpointParameters(123, 100.1, 'ASD_', 'ASD'); + + $headers = $fakeHttpClient->getLastRequest()->getHeaders(); + + $this->assertArrayHasKey('Authorization', $headers); + $encodedCredentials = base64_encode("$username:$password"); + $this->assertEquals(["Basic $encodedCredentials"], $headers['Authorization']); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/DateTimeSerializerTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/DateTimeSerializerTest.php new file mode 100644 index 000000000000..cea8db4a067e --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/DateTimeSerializerTest.php @@ -0,0 +1,34 @@ + $dateTime, + ]); + + $data = ObjectSerializer::sanitizeForSerialization($input); + + $this->assertEquals($data->dateTime, '1973-04-30T17:05:00+02:00'); + } + + public function testDateSanitazion() + { + $dateTime = new \DateTime('April 30, 1973 17:05 CEST'); + + $input = new FormatTest([ + 'date' => $dateTime, + ]); + + $data = ObjectSerializer::sanitizeForSerialization($input); + + $this->assertEquals($data->date, '1973-04-30'); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/DebugTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/DebugTest.php new file mode 100644 index 000000000000..f4deb922f568 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/DebugTest.php @@ -0,0 +1,36 @@ +setId(1); + $newPet->setName("PHP Unit Test"); + (new Api\PetApi())->addPetWithHttpInfo($newPet); + } + + public function testEnableDebugOutput() + { + $this->expectOutputRegex('#GET /v2/pet/1 HTTP/1.1#'); + + $config = new Configuration(); + $config->setDebug(true); + $api = new Api\PetApi(null, $config); + $api->getPetById(1); + } + + public function testEnableDebugOutputAsync() + { + $this->expectOutputRegex('#GET /v2/pet/1 HTTP/1.1#'); + + $config = new Configuration(); + $config->setDebug(true); + $api = new Api\PetApi(null, $config); + $promise = $api->getPetByIdAsync(1); + $promise->wait(); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/EnumClassTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/EnumClassTest.php new file mode 100644 index 000000000000..7ba9d0552bb0 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/EnumClassTest.php @@ -0,0 +1,15 @@ +assertSame(EnumClass::ABC, '_abc'); + $this->assertSame(EnumClass::EFG, '-efg'); + $this->assertSame(EnumClass::XYZ, '(xyz)'); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/EnumTestTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/EnumTestTest.php new file mode 100644 index 000000000000..9e4ea5892515 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/EnumTestTest.php @@ -0,0 +1,34 @@ +assertSame(EnumTest::ENUM_STRING_UPPER, "UPPER"); + $this->assertSame(EnumTest::ENUM_STRING_LOWER, "lower"); + $this->assertSame(EnumTest::ENUM_INTEGER_1, 1); + $this->assertSame(EnumTest::ENUM_INTEGER_MINUS_1, -1); + $this->assertSame(EnumTest::ENUM_NUMBER_1_DOT_1, 1.1); + $this->assertSame(EnumTest::ENUM_NUMBER_MINUS_1_DOT_2, -1.2); + } + + public function testNonRequiredPropertyIsOptional() + { + $enum = new EnumTest([ + 'enum_string_required' => 'UPPER', + ]); + $this->assertSame([], $enum->listInvalidProperties()); + $this->assertTrue($enum->valid()); + } + + public function testRequiredProperty() + { + $enum = new EnumTest(); + $this->assertSame(["'enum_string_required' can't be null"], $enum->listInvalidProperties()); + $this->assertFalse($enum->valid()); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php new file mode 100644 index 000000000000..29a0d5d75596 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php @@ -0,0 +1,41 @@ +setHost('http://petstore.swagger.io/INVALID_URL'); + + $api = new Api\StoreApi( + new Client(), + $config + ); + $api->getInventory(); + } + + /** + * @expectedException \Swagger\Client\ApiException + * @expectedExceptionMessage Could not resolve host + */ + public function testWrongHost() + { + $config = new Configuration(); + $config->setHost('http://wrong_host.zxc'); + + $api = new Api\StoreApi( + new Client(), + $config + ); + $api->getInventory(); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php new file mode 100644 index 000000000000..abdfa7cf7c2f --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php @@ -0,0 +1,69 @@ +request; + } + + /** + * @param null|ResponseInterface $response + */ + public function setResponse(ResponseInterface $response = null) + { + $this->response = $response; + } + + /** + * Send an HTTP request. + * + * @param RequestInterface $request Request to send + * @param array $options Request options to apply to the given + * request and to the transfer. + * + * @return ResponseInterface + * @throws GuzzleException + */ + public function send(RequestInterface $request, array $options = []) + { + $this->request = $request; + return $this->response ?: new Response(200); + } + + public function sendAsync(RequestInterface $request, array $options = []) + { + throw new \RuntimeException('not implemented'); + } + + public function request($method, $uri, array $options = []) + { + throw new \RuntimeException('not implemented'); + } + + public function requestAsync($method, $uri, array $options = []) + { + throw new \RuntimeException('not implemented'); + } + + public function getConfig($option = null) + { + throw new \RuntimeException('not implemented'); + } +} \ No newline at end of file diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php new file mode 100644 index 000000000000..7a89448f89e8 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php @@ -0,0 +1,56 @@ +selectHeaders([ + 'application/xml', + 'application/json' + ], []); + $this->assertSame('application/json', $headers['Accept']); + + $headers = $selector->selectHeaders([], []); + $this->assertArrayNotHasKey('Accept', $headers); + + $header = $selector->selectHeaders([ + 'application/yaml', + 'application/xml' + ], []); + $this->assertSame('application/yaml,application/xml', $header['Accept']); + + // test selectHeaderContentType + $headers = $selector->selectHeaders([], [ + 'application/xml', + 'application/json' + ]); + $this->assertSame('application/json', $headers['Content-Type']); + + $headers = $selector->selectHeaders([], []); + $this->assertSame('application/json', $headers['Content-Type']); + $headers = $selector->selectHeaders([], [ + 'application/yaml', + 'application/xml' + ]); + $this->assertSame('application/yaml,application/xml', $headers['Content-Type']); + } + + public function testSelectingHeadersForMultipartBody() + { + // test selectHeaderAccept + $selector = new HeaderSelector(); + $headers = $selector->selectHeadersForMultipart([ + 'application/xml', + 'application/json' + ]); + $this->assertSame('application/json', $headers['Accept']); + $this->assertArrayNotHasKey('Content-Type', $headers); + + $headers = $selector->selectHeadersForMultipart([]); + $this->assertArrayNotHasKey('Accept', $headers); + $this->assertArrayNotHasKey('Content-Type', $headers); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php new file mode 100644 index 000000000000..5431a912efed --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php @@ -0,0 +1,31 @@ +fakeHttpClient = new FakeHttpClient(); + } + + public function testUserAgent() + { + $config = new Configuration(); + $config->setUserAgent('value'); + $api = new Api\PetApi($this->fakeHttpClient, $config); + + $api->getPetById(3); + + $request = $this->fakeHttpClient->getLastRequest(); + $headers = $request->getHeaders(); + + $this->assertArrayHasKey('User-Agent', $headers); + $this->assertEquals(['value'], $headers['User-Agent']); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ModelInheritanceTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ModelInheritanceTest.php new file mode 100644 index 000000000000..658e60ba6384 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ModelInheritanceTest.php @@ -0,0 +1,96 @@ +assertSame('red', $dog->getColor()); + $this->assertSame('red', $animal->getColor()); + } + + /** + * test inheritance in the model + */ + public function testInheritance() + { + $newDog = new Dog; + // the object should be an instance of the derived class + $this->assertInstanceOf(Dog::class, $newDog); + // the object should also be an instance of the parent class + $this->assertInstanceOf(Animal::class, $newDog); + } + + /** + * test inheritance constructor is working with data initialization + */ + public function testInheritanceConstructorDataInitialization() + { + // initialize the object with data in the constructor + $data = [ + 'class_name' => 'Dog', + 'breed' => 'Great Dane', + ]; + $newDog = new Dog($data); + + // the property on the derived class should be set + $this->assertSame('Great Dane', $newDog->getBreed()); + // the property on the parent class should be set + $this->assertSame('Dog', $newDog->getClassName()); + } + + /** + * test if discriminator is initialized automatically + */ + public function testDiscriminatorInitialization() + { + $newDog = new Dog(); + $this->assertSame('Dog', $newDog->getClassName()); + } + + /** + * test if ArrayAccess interface works + */ + public function testArrayStuff() + { + // create an AnimalFarm which is an object implementing the ArrayAccess interface + $farm = new AnimalFarm(); + + // add some animals to the farm to make sure the ArrayAccess interface works + $farm[] = new Dog(); + $farm[] = new Cat(); + $farm[] = new Animal(); + + // assert we can look up the animals in the farm by array indices (let's try a random order) + $this->assertInstanceOf(Cat::class, $farm[1]); + $this->assertInstanceOf(Dog::class, $farm[0]); + $this->assertInstanceOf(Animal::class, $farm[2]); + + // let's try to `foreach` the animals in the farm and let's try to use the objects we loop through + foreach ($farm as $animal) { + $this->assertContains($animal->getClassName(), ['Dog', 'Cat', 'Animal']); + $this->assertInstanceOf('Swagger\Client\Model\Animal', $animal); + } + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php new file mode 100644 index 000000000000..ce147d0e9e2a --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php @@ -0,0 +1,25 @@ +assertSame("sun.gif", $s->sanitizeFilename("sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("../sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("/var/tmp/sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("./sun.gif")); + + $this->assertSame("sun", $s->sanitizeFilename("sun")); + $this->assertSame("sun.gif", $s->sanitizeFilename("..\sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("\var\tmp\sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("c:\var\tmp\sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename(".\sun.gif")); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php new file mode 100644 index 000000000000..8b5c8f7e499b --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php @@ -0,0 +1,133 @@ +assertSame(Model\Order::STATUS_PLACED, "placed"); + $this->assertSame(Model\Order::STATUS_APPROVED, "approved"); + } + + // test get inventory + public function testOrder() + { + // initialize the API client + $order = new Model\Order(); + + $order->setStatus("placed"); + $this->assertSame("placed", $order->getStatus()); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testOrderException() + { + // initialize the API client + $order = new Model\Order(); + $order->setStatus("invalid_value"); + } + + // test deseralization of order + public function testDeserializationOfOrder() + { + $order_json = <<assertInstanceOf('Swagger\Client\Model\Order', $order); + $this->assertSame(10, $order->getId()); + $this->assertSame(20, $order->getPetId()); + $this->assertSame(30, $order->getQuantity()); + $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $order->getShipDate()); + $this->assertSame("placed", $order->getStatus()); + $this->assertSame(false, $order->getComplete()); + } + + // test deseralization of array of array of order + public function testDeserializationOfArrayOfArrayOfOrder() + { + $order_json = <<assertArrayHasKey(0, $order); + $this->assertArrayHasKey(0, $order[0]); + $_order = $order[0][0]; + $this->assertInstanceOf('Swagger\Client\Model\Order', $_order); + $this->assertSame(10, $_order->getId()); + $this->assertSame(20, $_order->getPetId()); + $this->assertSame(30, $_order->getQuantity()); + $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); + $this->assertSame("placed", $_order->getStatus()); + $this->assertSame(false, $_order->getComplete()); + } + + // test deseralization of map of map of order + public function testDeserializationOfMapOfMapOfOrder() + { + $order_json = <<assertArrayHasKey('test', $order); + $this->assertArrayHasKey('test2', $order['test']); + $_order = $order['test']['test2']; + $this->assertInstanceOf('Swagger\Client\Model\Order', $_order); + $this->assertSame(10, $_order->getId()); + $this->assertSame(20, $_order->getPetId()); + $this->assertSame(30, $_order->getQuantity()); + $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); + $this->assertSame("placed", $_order->getStatus()); + $this->assertSame(false, $_order->getComplete()); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/OuterEnumTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/OuterEnumTest.php new file mode 100644 index 000000000000..d7d12d5cbb88 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/OuterEnumTest.php @@ -0,0 +1,94 @@ +assertInternalType('string', $result); + $this->assertEquals('placed', $result); + } + + public function testDeserializeInvalidValue() + { + $this->setExpectedException(\InvalidArgumentException::class, 'Invalid value for enum'); + + ObjectSerializer::deserialize( + "lkjfalgkdfjg", + OuterEnum::class + ); + } + + public function testDeserializeNested() + { + $json = '{ + "enum_string": "UPPER", + "enum_integer": -1, + "enum_number": -1.2, + "outerEnum": "approved" + }'; + + /** * @var EnumTest $result */ + $result = ObjectSerializer::deserialize( + json_decode($json), + EnumTest::class + ); + + $this->assertInstanceOf(EnumTest::class, $result); + $this->assertEquals('approved', $result->getOuterEnum()); + } + + public function testSanitize() + { + $json = "placed"; + + $result = ObjectSerializer::sanitizeForSerialization( + $json + ); + + $this->assertInternalType('string', $result); + } + + public function testSanitizeNested() + { + $input = new EnumTest([ + 'enum_string' => 'UPPER', + 'enum_integer' => -1, + 'enum_number' => -1.2, + 'outer_enum' => 'approved' + ]); + + $result = ObjectSerializer::sanitizeForSerialization( + $input + ); + + $this->assertInternalType('object', $result); + $this->assertInstanceOf(\stdClass::class, $result); + + $this->assertInternalType('string', $result->outerEnum); + $this->assertEquals('approved', $result->outerEnum); + } + + public function testSanitizeNestedInvalidValue() + { + $this->setExpectedException(\InvalidArgumentException::class, 'Invalid value for enum'); + + $input = new EnumTest([ + 'enum_string' => 'UPPER', + 'enum_integer' => -1, + 'enum_number' => -1.2, + 'outer_enum' => 'invalid_value' + ]); + + ObjectSerializer::sanitizeForSerialization($input); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ParametersTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ParametersTest.php new file mode 100644 index 000000000000..e5d47d61d932 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ParametersTest.php @@ -0,0 +1,65 @@ +fakeHttpClient = new FakeHttpClient(); + $this->fakeApi = new Api\FakeApi($this->fakeHttpClient); + $this->userApi = new Api\UserApi($this->fakeHttpClient); + } + + public function testHeaderParam() + { + $this->fakeApi->testEnumParameters([], 'something'); + + $request = $this->fakeHttpClient->getLastRequest(); + $headers = $request->getHeaders(); + + $this->assertArrayHasKey('enum_header_string', $headers); + $this->assertEquals(['something'], $headers['enum_header_string']); + } + + public function testHeaderParamCollection() + { + $this->fakeApi->testEnumParameters(['string1', 'string2']); + + $request = $this->fakeHttpClient->getLastRequest(); + $headers = $request->getHeaders(); + + $this->assertArrayHasKey('enum_header_string_array', $headers); + $this->assertEquals(['string1,string2'], $headers['enum_header_string_array']); + } + + public function testInlineAdditionalProperties() + { + $param = new \stdClass(); + $param->foo = 'bar'; + $this->fakeApi->testInlineAdditionalProperties($param); + + $request = $this->fakeHttpClient->getLastRequest(); + $this->assertSame('{"foo":"bar"}', $request->getBody()->getContents()); + } + +// missing example for collection path param in config +// public function testPathParamCollection() +// { +// $this->userApi->getUserByNameWithHttpInfo(['aa', 'bb']); +// $request = $this->fakeHttpClient->getLastRequest(); +// $this->assertEquals('user/aa,bb', urldecode($request->getUri()->getPath())); +// } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php new file mode 100644 index 000000000000..be834d9dda6a --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -0,0 +1,390 @@ +setId($newPetId); + $newPet->setName("PHP Unit Test"); + $newPet->setPhotoUrls(["http://test_php_unit_test.com"]); + // new tag + $tag = new Model\Tag; + $tag->setId($newPetId); // use the same id as pet + $tag->setName("test php tag"); + // new category + $category = new Model\Category; + $category->setId($newPetId); // use the same id as pet + $category->setName("test php category"); + + $newPet->setTags(array($tag)); + $newPet->setCategory($category); + + $config = new Configuration(); + $petApi = new Api\PetApi(null, $config); + + // add a new pet (model) + list(, $status) = $petApi->addPetWithHttpInfo($newPet); + \PHPUnit_Framework_Assert::assertEquals(200, $status); + } + + public function setUp() + { + $this->api = new Api\PetApi(); + } + + public function testGetPetById() + { + $petId = 10005; + + $pet = $this->api->getPetById($petId); + $this->assertSame($pet->getId(), $petId); + $this->assertSame($pet->getName(), 'PHP Unit Test'); + $this->assertSame($pet->getPhotoUrls()[0], 'http://test_php_unit_test.com'); + $this->assertSame($pet->getCategory()->getId(), $petId); + $this->assertSame($pet->getCategory()->getName(), 'test php category'); + $this->assertSame($pet->getTags()[0]->getId(), $petId); + $this->assertSame($pet->getTags()[0]->getName(), 'test php tag'); + } + + /** + * comment out as we've removed invalid endpoints from the spec, we'll introduce something + * similar in the future when we've time to update the petstore server + * + * // test getPetById with a Pet object (id 10005) + * public function testGetPetByIdInObject() + * { + * // initialize the API client without host + * $pet_id = 10005; // ID of pet that needs to be fetched + * $pet_api = new Api\PetApi(); + * $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); + * // return Pet (inline model) + * $response = $pet_api->getPetByIdInObject($pet_id); + * $this->assertInstanceOf('Swagger\Client\Model\InlineResponse200', $response); + * $this->assertSame($response->getId(), $pet_id); + * $this->assertSame($response->getName(), 'PHP Unit Test'); + * $this->assertSame($response->getPhotoUrls()[0], 'http://test_php_unit_test.com'); + * + * // category is type "object" + * $this->assertInternalType('array', $response->getCategory()); + * $this->assertSame($response->getCategory()['id'], $pet_id); + * $this->assertSame($response->getCategory()['name'], 'test php category'); + * + * $this->assertSame($response->getTags()[0]->getId(), $pet_id); + * $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); + * } + */ + + // test getPetByIdWithHttpInfo with a Pet object (id 10005) + public function testGetPetByIdWithHttpInfo() + { + // initialize the API client without host + $petId = 10005; // ID of pet that needs to be fetched + + /** @var $pet Pet */ + list($pet, $status_code, $response_headers) = $this->api->getPetByIdWithHttpInfo($petId); + $this->assertSame($pet->getId(), $petId); + $this->assertSame($pet->getName(), 'PHP Unit Test'); + $this->assertSame($pet->getCategory()->getId(), $petId); + $this->assertSame($pet->getCategory()->getName(), 'test php category'); + $this->assertSame($pet->getTags()[0]->getId(), $petId); + $this->assertSame($pet->getTags()[0]->getName(), 'test php tag'); + $this->assertSame($status_code, 200); + $this->assertSame($response_headers['Content-Type'], ['application/json']); + } + + public function testFindPetByStatus() + { + $response = $this->api->findPetsByStatus('available'); + $this->assertGreaterThan(0, count($response)); // at least one object returned + + $this->assertSame(get_class($response[0]), Pet::class); // verify the object is Pet + foreach ($response as $pet) { + $this->assertSame($pet['status'], 'available'); + } + + $response = $this->api->findPetsByStatus('unknown_and_incorrect_status'); + $this->assertCount(0, $response); + } + + public function testUpdatePet() + { + $petId = 10001; + $updatedPet = new Model\Pet; + $updatedPet->setId($petId); + $updatedPet->setName('updatePet'); + $updatedPet->setStatus('pending'); + $result = $this->api->updatePet($updatedPet); + $this->assertNull($result); + + // verify updated Pet + $result = $this->api->getPetById($petId); + $this->assertSame($result->getId(), $petId); + $this->assertSame($result->getStatus(), 'pending'); + $this->assertSame($result->getName(), 'updatePet'); + } + + // test updatePetWithFormWithHttpInfo and verify by the "name" of the response + public function testUpdatePetWithFormWithHttpInfo() + { + $petId = 10001; // ID of pet that needs to be fetched + + // update Pet (form) + list($update_response, $status_code, $http_headers) = $this->api->updatePetWithFormWithHttpInfo( + $petId, + 'update pet with form with http info' + ); + // return nothing (void) + $this->assertNull($update_response); + $this->assertSame($status_code, 200); + $this->assertSame($http_headers['Content-Type'], ['application/json']); + $response = $this->api->getPetById($petId); + $this->assertSame($response->getId(), $petId); + $this->assertSame($response->getName(), 'update pet with form with http info'); + } + + // test updatePetWithForm and verify by the "name" and "status" of the response + public function testUpdatePetWithForm() + { + $pet_id = 10001; // ID of pet that needs to be fetched + $result = $this->api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); + // return nothing (void) + $this->assertNull($result); + + $response = $this->api->getPetById($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'update pet with form'); + $this->assertSame($response->getStatus(), 'sold'); + } + + // test addPet and verify by the "id" and "name" of the response + public function testAddPet() + { + $new_pet_id = 10005; + $newPet = new Model\Pet; + $newPet->setId($new_pet_id); + $newPet->setName("PHP Unit Test 2"); + + // add a new pet (model) + $add_response = $this->api->addPet($newPet); + // return nothing (void) + $this->assertNull($add_response); + + // verify added Pet + $response = $this->api->getPetById($new_pet_id); + $this->assertSame($response->getId(), $new_pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test 2'); + } + + /* + * comment out as we've removed invalid endpoints from the spec, we'll introduce something + * similar in the future when we've time to update the petstore server + * + // test addPetUsingByteArray and verify by the "id" and "name" of the response + public function testAddPetUsingByteArray() + { + // initialize the API client + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + + $new_pet_id = 10005; + $new_pet = new Model\Pet; + $new_pet->setId($new_pet_id); + $new_pet->setName("PHP Unit Test 3"); + // new tag + $tag= new Model\Tag; + $tag->setId($new_pet_id); // use the same id as pet + $tag->setName("test php tag"); + // new category + $category = new Model\Category; + $category->setId($new_pet_id); // use the same id as pet + $category->setName("test php category"); + + $new_pet->setTags(array($tag)); + $new_pet->setCategory($category); + + $pet_api = new Api\PetApi($api_client); + // add a new pet (model) + $object_serializer = new ObjectSerializer(); + $pet_json_string = json_encode($object_serializer->sanitizeForSerialization($new_pet)); + $add_response = $pet_api->addPetUsingByteArray($pet_json_string); + // return nothing (void) + $this->assertSame($add_response, NULL); + // verify added Pet + $response = $pet_api->getPetById($new_pet_id); + $this->assertSame($response->getId(), $new_pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test 3'); + } + */ + + // test upload file + public function testUploadFile() + { + // upload file + $pet_id = 10001; + $response = $this->api->uploadFile($pet_id, 'test meta', __DIR__ . '/../composer.json'); + // return ApiResponse + $this->assertInstanceOf(ApiResponse::class, $response); + } + + /* + * comment out as we've removed invalid endpoints from the spec, we'll introduce something + * similar in the future when we've time to update the petstore server + * + // test byte array response + public function testGetPetByIdWithByteArray() + { + // initialize the API client + $config = new Configuration(); + $config->setHost('http://petstore.swagger.io/v2'); + $api_client = new APIClient($config); + $pet_api = new Api\PetApi($api_client); + // test getPetByIdWithByteArray + $pet_id = 10005; + $bytes = $pet_api->petPetIdtestingByteArraytrueGet($pet_id); + $json = json_decode($bytes, true); + + $this->assertInternalType("string", $bytes); + + $this->assertSame($json['id'], $pet_id); + // not testing name as it's tested by addPetUsingByteArray + //$this->assertSame($json['name'], 'PHP Unit Test'); + $this->assertSame($json['category']['id'], $pet_id); + $this->assertSame($json['category']['name'], 'test php category'); + $this->assertSame($json['tags'][0]['id'], $pet_id); + $this->assertSame($json['tags'][0]['name'], 'test php tag'); + } + */ + + // test empty object serialization + public function testEmptyPetSerialization() + { + $new_pet = new Model\Pet; + // the empty object should be serialised to {} + $this->assertSame("{}", "$new_pet"); + } + + // test inheritance in the model + public function testInheritance() + { + $new_dog = new Model\Dog; + // the object should be an instance of the derived class + $this->assertInstanceOf('Swagger\Client\Model\Dog', $new_dog); + // the object should also be an instance of the parent class + $this->assertInstanceOf('Swagger\Client\Model\Animal', $new_dog); + } + + // test inheritance constructor is working with data + // initialization + public function testInheritanceConstructorDataInitialization() + { + // initialize the object with data in the constructor + $data = array( + 'class_name' => 'Dog', + 'breed' => 'Great Dane' + ); + $new_dog = new Model\Dog($data); + + // the property on the derived class should be set + $this->assertSame('Great Dane', $new_dog->getBreed()); + // the property on the parent class should be set + $this->assertSame('Dog', $new_dog->getClassName()); + } + + // test if discriminator is initialized automatically + public function testDiscriminatorInitialization() + { + $new_dog = new Model\Dog(); + $this->assertSame('Dog', $new_dog->getClassName()); + } + + // test if ArrayAccess interface works + public function testArrayStuff() + { + // create an AnimalFarm which is an object implementing the + // ArrayAccess interface + $farm = new Model\AnimalFarm(); + + // add some animals to the farm to make sure the ArrayAccess + // interface works + $farm[] = new Model\Dog(); + $farm[] = new Model\Cat(); + $farm[] = new Model\Animal(); + + // assert we can look up the animals in the farm by array + // indices (let's try a random order) + $this->assertInstanceOf('Swagger\Client\Model\Cat', $farm[1]); + $this->assertInstanceOf('Swagger\Client\Model\Dog', $farm[0]); + $this->assertInstanceOf('Swagger\Client\Model\Animal', $farm[2]); + + // let's try to `foreach` the animals in the farm and let's + // try to use the objects we loop through + foreach ($farm as $animal) { + $this->assertContains($animal->getClassName(), array('Dog', 'Cat', 'Animal')); + $this->assertInstanceOf('Swagger\Client\Model\Animal', $animal); + } + } + + // test if default values works + public function testDefaultValues() + { + // add some animals to the farm to make sure the ArrayAccess + // interface works + $dog = new Model\Dog(); + $animal = new Model\Animal(); + + // assert we can look up the animals in the farm by array + // indices (let's try a random order) + $this->assertSame('red', $dog->getColor()); + $this->assertSame('red', $animal->getColor()); + } + + /** + * test invalid argument + * + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Missing the required parameter $status when calling findPetsByStatus + */ + public function testInvalidArgument() + { + // the argument is required, and we must specify one or some from 'available', 'pending', 'sold' + $this->api->findPetsByStatus([]); + } + +// Disabled as currently we don't have any endpoint that would return file +// For testing I just replaced url and return type in Api method. +// public function testDownloadingLargeFile() +// { +// $petId = 10005; +// $config = new Configuration(); +// $config->setHost('https://getcomposer.org'); +// $api = new PetApi(new Client(), $config); +// $result = $api->getPetById($petId); +// $this->assertInstanceOf(\SplFileObject::class, $result); +// var_dump([ +// 'peak mem (MiB)' => memory_get_peak_usage(true)/1024/1024, +// 'file size (MiB)' => $result->getSize()/1024/1024, +// 'path' => sys_get_temp_dir() . '/' . $result->getFilename() +// ]); +// } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/PetTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/PetTest.php new file mode 100644 index 000000000000..60ce604c5226 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/PetTest.php @@ -0,0 +1,18 @@ +assertSame("{}", "$new_pet"); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/RequestTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/RequestTest.php new file mode 100644 index 000000000000..2fd9ab8831f2 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/RequestTest.php @@ -0,0 +1,43 @@ +fakeClient = new FakeHttpClient(); + $this->api = new Api\FakeApi($this->fakeClient); + } + + public function testFormDataEncodingToJson() + { + $this->api->testJsonFormData( + new Body4(['param' => 'value', 'param2' => 'value2']) + ); + + $request = $this->fakeClient->getLastRequest(); + $contentType = $request->getHeader('Content-Type'); + $this->assertEquals(['application/json'], $contentType); + + $requestContent = $request->getBody()->getContents(); + $expected = <<<__EOS__ +{ + "param": "value", + "param2": "value2" +} +__EOS__; + + $this->assertEquals($expected, $requestContent); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ResponseTypesTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ResponseTypesTest.php new file mode 100644 index 000000000000..71eda338ba90 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/ResponseTypesTest.php @@ -0,0 +1,95 @@ +fakeHttpClient = new FakeHttpClient(); + $this->api = new PetApi($this->fakeHttpClient); + } + + public function testDefined200ReturnType() + { + $this->fakeHttpClient->setResponse(new Response(200, [], json_encode([]))); + $result = $this->api->getPetById(123); + + $this->assertInstanceOf(Pet::class, $result); + } + + public function testDefault2xxReturnType() + { + $this->fakeHttpClient->setResponse(new Response(255, [], json_encode([]))); + $result = $this->api->getPetById(123); + + $this->assertInstanceOf(Pet::class, $result); + } + + /** + * @expectedException \Swagger\Client\ApiException + * @expectedExceptionCode 400 + */ + public function testDefinedErrorException() + { + $statusCode = 400; + + $this->fakeHttpClient->setResponse(new Response($statusCode, [], '{}')); + $this->api->getPetById(123); + } + +// missing case in spec: +// responses: +// '400': +// description: failure +// schema: +// $ref: '#/definitions/Error' +// public function testDefinedErrorResponseObject() +// { +// $result = null; +// try { +// $this->fakeHttpClient->setResponse(new Response(400, [], '{}')); +// $this->api->getPetById(123); +// } catch (ApiException $e) { +// $result = $e->getResponseObject(); +// } +// +// $this->assertInstanceOf(Error::class, $result); +// } + + /** + * @expectedException \Swagger\Client\ApiException + * @expectedExceptionCode 404 + */ + public function testDefaultErrorException() + { + $statusCode = 404; + + $this->fakeHttpClient->setResponse(new Response($statusCode, [], '{}')); + $this->api->getPetById(123); + } + + public function testDefaultErrorResponseObject() + { + $result = null; + try { + $this->fakeHttpClient->setResponse(new Response(404, [], '{}')); + $this->api->getPetById(123); + } catch (ApiException $e) { + $result = $e->getResponseObject(); + } + + $this->assertNull($result); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php new file mode 100644 index 000000000000..3af84b8d8513 --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -0,0 +1,56 @@ +api = new StoreApi(); + } + + /** + * Setup before running each test case + */ + public static function setUpBeforeClass() + { + // add a new pet (id 10005) to ensure the pet object is available for all the tests + // new pet + $id = 10005; + $pet = new Pet(); + $pet->setId($id); + $pet->setName('PHP Unit Test'); + $pet->setStatus('available'); + // new tag + $tag = new Tag(); + $tag->setId($id); // use the same id as pet + $tag->setName('test php tag'); + // new category + $category = new Category(); + $category->setId($id); // use the same id as pet + $category->setName('test php category'); + + $pet->setTags([$tag]); + $pet->setCategory($category); + + $api = new PetApi(); + $api->addPet($pet); + } + + public function testGetInventory() + { + $result = $this->api->getInventory(); + + $this->assertInternalType('array', $result); + $this->assertInternalType('int', $result['available']); + } +} diff --git a/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php new file mode 100644 index 000000000000..7d6dfcfc1f4f --- /dev/null +++ b/samples/openapi3/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -0,0 +1,32 @@ +api = new Api\UserApi(); + } + + // test login use + public function testLoginUser() + { + // initialize the API client + // login + $response = $this->api->loginUser('xxxxx', 'yyyyyyyy'); + + $this->assertInternalType('string', $response); + $this->assertRegExp( + '/^logged in user session/', + $response, + "response string starts with 'logged in user session'" + ); + } +} diff --git a/samples/server/petstore/aspnetcore/.swagger-codegen/VERSION b/samples/server/petstore/aspnetcore/.swagger-codegen/VERSION index 855ff9501eb8..096bf47efe31 100644 --- a/samples/server/petstore/aspnetcore/.swagger-codegen/VERSION +++ b/samples/server/petstore/aspnetcore/.swagger-codegen/VERSION @@ -1 +1 @@ -2.4.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/PetApi.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/PetApi.cs index 88dfc690ef1b..4cf8b11034ab 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/PetApi.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/PetApi.cs @@ -35,13 +35,13 @@ public class PetApiController : Controller /// Add a new pet to the store ///

- /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store /// Invalid input [HttpPost] [Route("/v2/pet")] [ValidateModelState] [SwaggerOperation("AddPet")] - public virtual IActionResult AddPet([FromBody]Pet body) + public virtual IActionResult AddPet([FromBody]Pet pet) { //TODO: Uncomment the next line to return response 405 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(405); @@ -91,8 +91,8 @@ public virtual IActionResult FindPetsByStatus([FromQuery][Required()]List>(exampleJson) @@ -122,8 +122,8 @@ public virtual IActionResult FindPetsByTags([FromQuery][Required()]List // return StatusCode(400); string exampleJson = null; + exampleJson = "{\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n}"; exampleJson = "\n 123456789\n doggie\n \n aeiou\n \n \n \n aeiou\n"; - exampleJson = "[ {\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n}, {\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n} ]"; var example = exampleJson != null ? JsonConvert.DeserializeObject>(exampleJson) @@ -157,8 +157,8 @@ public virtual IActionResult GetPetById([FromRoute][Required]long? petId) // return StatusCode(404); string exampleJson = null; - exampleJson = "\n 123456789\n doggie\n \n aeiou\n \n \n \n aeiou\n"; exampleJson = "{\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n}"; + exampleJson = "\n 123456789\n doggie\n \n aeiou\n \n \n \n aeiou\n"; var example = exampleJson != null ? JsonConvert.DeserializeObject(exampleJson) @@ -171,7 +171,7 @@ public virtual IActionResult GetPetById([FromRoute][Required]long? petId) /// Update an existing pet ///
- /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store /// Invalid ID supplied /// Pet not found /// Validation exception @@ -179,7 +179,7 @@ public virtual IActionResult GetPetById([FromRoute][Required]long? petId) [Route("/v2/pet")] [ValidateModelState] [SwaggerOperation("UpdatePet")] - public virtual IActionResult UpdatePet([FromBody]Pet body) + public virtual IActionResult UpdatePet([FromBody]Pet pet) { //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(400); diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/StoreApi.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/StoreApi.cs index d2ee6867e7f1..0958764c07bb 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/StoreApi.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/StoreApi.cs @@ -104,8 +104,8 @@ public virtual IActionResult GetOrderById([FromRoute][Required][Range(1, 5)]long // return StatusCode(404); string exampleJson = null; - exampleJson = "\n 123456789\n 123456789\n 123\n 2000-01-23T04:56:07.000Z\n aeiou\n true\n"; exampleJson = "{\n \"petId\" : 6,\n \"quantity\" : 1,\n \"id\" : 0,\n \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\",\n \"complete\" : false,\n \"status\" : \"placed\"\n}"; + exampleJson = "\n 123456789\n 123456789\n 123\n 2000-01-23T04:56:07.000Z\n aeiou\n true\n"; var example = exampleJson != null ? JsonConvert.DeserializeObject(exampleJson) @@ -118,7 +118,7 @@ public virtual IActionResult GetOrderById([FromRoute][Required][Range(1, 5)]long /// Place an order for a pet ///
- /// order placed for purchasing the pet + /// order placed for purchasing the pet /// successful operation /// Invalid Order [HttpPost] @@ -126,7 +126,7 @@ public virtual IActionResult GetOrderById([FromRoute][Required][Range(1, 5)]long [ValidateModelState] [SwaggerOperation("PlaceOrder")] [SwaggerResponse(statusCode: 200, type: typeof(Order), description: "successful operation")] - public virtual IActionResult PlaceOrder([FromBody]Order body) + public virtual IActionResult PlaceOrder([FromBody]Order order) { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(200, default(Order)); @@ -135,8 +135,8 @@ public virtual IActionResult PlaceOrder([FromBody]Order body) // return StatusCode(400); string exampleJson = null; - exampleJson = "\n 123456789\n 123456789\n 123\n 2000-01-23T04:56:07.000Z\n aeiou\n true\n"; exampleJson = "{\n \"petId\" : 6,\n \"quantity\" : 1,\n \"id\" : 0,\n \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\",\n \"complete\" : false,\n \"status\" : \"placed\"\n}"; + exampleJson = "\n 123456789\n 123456789\n 123\n 2000-01-23T04:56:07.000Z\n aeiou\n true\n"; var example = exampleJson != null ? JsonConvert.DeserializeObject(exampleJson) diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/UserApi.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/UserApi.cs index 5a616057f9c6..876f47a420d8 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/UserApi.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Controllers/UserApi.cs @@ -35,13 +35,13 @@ public class UserApiController : Controller /// Create user ///
/// This can only be done by the logged in user. - /// Created user object + /// Created user object /// successful operation [HttpPost] [Route("/v2/user")] [ValidateModelState] [SwaggerOperation("CreateUser")] - public virtual IActionResult CreateUser([FromBody]User body) + public virtual IActionResult CreateUser([FromBody]User user) { //TODO: Uncomment the next line to return response 0 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(0); @@ -54,13 +54,13 @@ public virtual IActionResult CreateUser([FromBody]User body) /// Creates list of users with given input array ///
- /// List of user object + /// List of user object /// successful operation [HttpPost] [Route("/v2/user/createWithArray")] [ValidateModelState] [SwaggerOperation("CreateUsersWithArrayInput")] - public virtual IActionResult CreateUsersWithArrayInput([FromBody]List body) + public virtual IActionResult CreateUsersWithArrayInput([FromBody]List user) { //TODO: Uncomment the next line to return response 0 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(0); @@ -73,13 +73,13 @@ public virtual IActionResult CreateUsersWithArrayInput([FromBody]List body /// Creates list of users with given input array /// - /// List of user object + /// List of user object /// successful operation [HttpPost] [Route("/v2/user/createWithList")] [ValidateModelState] [SwaggerOperation("CreateUsersWithListInput")] - public virtual IActionResult CreateUsersWithListInput([FromBody]List body) + public virtual IActionResult CreateUsersWithListInput([FromBody]List user) { //TODO: Uncomment the next line to return response 0 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(0); @@ -115,7 +115,7 @@ public virtual IActionResult DeleteUser([FromRoute][Required]string username) /// Get user by user name /// - /// The name that needs to be fetched. Use user1 for testing. + /// The name that needs to be fetched. Use user1 for testing. /// successful operation /// Invalid username supplied /// User not found @@ -136,8 +136,8 @@ public virtual IActionResult GetUserByName([FromRoute][Required]string username) // return StatusCode(404); string exampleJson = null; - exampleJson = "\n 123456789\n aeiou\n aeiou\n aeiou\n aeiou\n aeiou\n aeiou\n 123\n"; exampleJson = "{\n \"firstName\" : \"firstName\",\n \"lastName\" : \"lastName\",\n \"password\" : \"password\",\n \"userStatus\" : 6,\n \"phone\" : \"phone\",\n \"id\" : 0,\n \"email\" : \"email\",\n \"username\" : \"username\"\n}"; + exampleJson = "\n 123456789\n aeiou\n aeiou\n aeiou\n aeiou\n aeiou\n aeiou\n 123\n"; var example = exampleJson != null ? JsonConvert.DeserializeObject(exampleJson) @@ -168,8 +168,8 @@ public virtual IActionResult LoginUser([FromQuery][Required()]string username, [ // return StatusCode(400); string exampleJson = null; - exampleJson = "aeiou"; exampleJson = "\"\""; + exampleJson = "aeiou"; var example = exampleJson != null ? JsonConvert.DeserializeObject(exampleJson) @@ -201,14 +201,14 @@ public virtual IActionResult LogoutUser() /// /// This can only be done by the logged in user. /// name that need to be deleted - /// Updated user object + /// Updated user object /// Invalid user supplied /// User not found [HttpPut] [Route("/v2/user/{username}")] [ValidateModelState] [SwaggerOperation("UpdateUser")] - public virtual IActionResult UpdateUser([FromRoute][Required]string username, [FromBody]User body) + public virtual IActionResult UpdateUser([FromRoute][Required]string username, [FromBody]User user) { //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(400); diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Dockerfile b/samples/server/petstore/aspnetcore/src/IO.Swagger/Dockerfile index 66c2e7fdd23b..6b07232e561d 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Dockerfile +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Dockerfile @@ -1,11 +1,18 @@ -FROM microsoft/dotnet:1.0.3-sdk-projectjson +FROM microsoft/aspnetcore-build:2.0 AS build-env +WORKDIR /app ENV DOTNET_CLI_TELEMETRY_OPTOUT 1 -WORKDIR /app/IO.Swagger -COPY . /app/IO.Swagger +# copy csproj and restore as distinct layers +COPY *.csproj ./ +RUN dotnet restore -EXPOSE 5000/tcp +# copy everything else and build +COPY . ./ +RUN dotnet publish -c Release -o out -RUN ["dotnet", "restore"] -ENTRYPOINT ["dotnet", "run", "-p", "project.json", "web"] +# build runtime image +FROM microsoft/aspnetcore:2.0 +WORKDIR /app +COPY --from=build-env /app/out . +ENTRYPOINT ["dotnet", "IO.Swagger.dll"] diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Startup.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Startup.cs index b62913042eba..5ed0ba5e50ff 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Startup.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Startup.cs @@ -71,7 +71,7 @@ public void ConfigureServices(IServiceCollection services) Contact = new Contact() { Name = "Swagger Codegen Contributors", - Url = "https://github.com/swagger-api/swagger-codegen", + Url = "https://github.com/openapitools/openapi-generator", Email = "apiteam@swagger.io" }, TermsOfService = "http://swagger.io/terms/" @@ -104,10 +104,10 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF .UseSwaggerUI(c => { //TODO: Either use the SwaggerGen generated Swagger contract (generated from C# classes) - c.SwaggerEndpoint("/swagger/1.0.0/swagger.json", "Swagger Petstore"); + c.SwaggerEndpoint("/swagger/1.0.0/openapi.json", "Swagger Petstore"); //TODO: Or alternatively use the original Swagger contract that's included in the static files - // c.SwaggerEndpoint("/swagger-original.json", "Swagger Petstore Original"); + // c.SwaggerEndpoint("/openapi-original.json", "Swagger Petstore Original"); }); if (env.IsDevelopment()) diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/wwwroot/openapi-original.json b/samples/server/petstore/aspnetcore/src/IO.Swagger/wwwroot/openapi-original.json new file mode 100644 index 000000000000..623d2993a609 --- /dev/null +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/wwwroot/openapi-original.json @@ -0,0 +1,1019 @@ +{ + "openapi" : "3.0.1", + "info" : { + "title" : "Swagger Petstore", + "description" : "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "termsOfService" : "http://swagger.io/terms/", + "contact" : { + "email" : "apiteam@swagger.io" + }, + "license" : { + "name" : "Apache-2.0", + "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version" : "1.0.0" + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" + }, + "servers" : [ { + "url" : "http://petstore.swagger.io/v2" + } ], + "tags" : [ { + "name" : "pet", + "description" : "Everything about your Pets", + "externalDocs" : { + "description" : "Find out more", + "url" : "http://swagger.io" + } + }, { + "name" : "store", + "description" : "Access to Petstore orders" + }, { + "name" : "user", + "description" : "Operations about user", + "externalDocs" : { + "description" : "Find out more about our store", + "url" : "http://swagger.io" + } + } ], + "paths" : { + "/pet" : { + "put" : { + "tags" : [ "pet" ], + "summary" : "Update an existing pet", + "operationId" : "updatePet", + "requestBody" : { + "description" : "Pet object that needs to be added to the store", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "required" : true + }, + "responses" : { + "400" : { + "description" : "Invalid ID supplied", + "content" : { } + }, + "404" : { + "description" : "Pet not found", + "content" : { } + }, + "405" : { + "description" : "Validation exception", + "content" : { } + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + }, + "post" : { + "tags" : [ "pet" ], + "summary" : "Add a new pet to the store", + "operationId" : "addPet", + "requestBody" : { + "description" : "Pet object that needs to be added to the store", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "required" : true + }, + "responses" : { + "405" : { + "description" : "Invalid input", + "content" : { } + } + }, + "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", + "parameters" : [ { + "name" : "status", + "in" : "query", + "description" : "Status values that need to be considered for filter", + "required" : true, + "explode" : false, + "schema" : { + "type" : "array", + "items" : { + "type" : "string", + "default" : "available", + "enum" : [ "available", "pending", "sold" ] + } + } + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "content" : { + "application/xml" : { + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "application/json" : { + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/components/schemas/Pet" + } + } + } + } + }, + "400" : { + "description" : "Invalid status value", + "content" : { } + } + }, + "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", + "parameters" : [ { + "name" : "tags", + "in" : "query", + "description" : "Tags to filter by", + "required" : true, + "explode" : false, + "schema" : { + "type" : "array", + "items" : { + "type" : "string" + } + } + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "content" : { + "application/xml" : { + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "application/json" : { + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/components/schemas/Pet" + } + } + } + } + }, + "400" : { + "description" : "Invalid tag value", + "content" : { } + } + }, + "deprecated" : true, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/pet/{petId}" : { + "get" : { + "tags" : [ "pet" ], + "summary" : "Find pet by ID", + "description" : "Returns a single pet", + "operationId" : "getPetById", + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet to return", + "required" : true, + "schema" : { + "type" : "integer", + "format" : "int64" + } + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + } + }, + "400" : { + "description" : "Invalid ID supplied", + "content" : { } + }, + "404" : { + "description" : "Pet not found", + "content" : { } + } + }, + "security" : [ { + "api_key" : [ ] + } ] + }, + "post" : { + "tags" : [ "pet" ], + "summary" : "Updates a pet in the store with form data", + "operationId" : "updatePetWithForm", + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet that needs to be updated", + "required" : true, + "schema" : { + "type" : "integer", + "format" : "int64" + } + } ], + "requestBody" : { + "content" : { + "application/x-www-form-urlencoded" : { + "schema" : { + "properties" : { + "name" : { + "type" : "string", + "description" : "Updated name of the pet" + }, + "status" : { + "type" : "string", + "description" : "Updated status of the pet" + } + } + } + } + } + }, + "responses" : { + "405" : { + "description" : "Invalid input", + "content" : { } + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + }, + "delete" : { + "tags" : [ "pet" ], + "summary" : "Deletes a pet", + "operationId" : "deletePet", + "parameters" : [ { + "name" : "api_key", + "in" : "header", + "schema" : { + "type" : "string" + } + }, { + "name" : "petId", + "in" : "path", + "description" : "Pet id to delete", + "required" : true, + "schema" : { + "type" : "integer", + "format" : "int64" + } + } ], + "responses" : { + "400" : { + "description" : "Invalid pet value", + "content" : { } + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/pet/{petId}/uploadImage" : { + "post" : { + "tags" : [ "pet" ], + "summary" : "uploads an image", + "operationId" : "uploadFile", + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet to update", + "required" : true, + "schema" : { + "type" : "integer", + "format" : "int64" + } + } ], + "requestBody" : { + "content" : { + "multipart/form-data" : { + "schema" : { + "properties" : { + "additionalMetadata" : { + "type" : "string", + "description" : "Additional data to pass to server" + }, + "file" : { + "type" : "string", + "description" : "file to upload", + "format" : "binary" + } + } + } + } + } + }, + "responses" : { + "200" : { + "description" : "successful operation", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/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", + "responses" : { + "200" : { + "description" : "successful operation", + "content" : { + "application/json" : { + "schema" : { + "type" : "object", + "additionalProperties" : { + "type" : "integer", + "format" : "int32" + } + } + } + } + } + }, + "security" : [ { + "api_key" : [ ] + } ] + } + }, + "/store/order" : { + "post" : { + "tags" : [ "store" ], + "summary" : "Place an order for a pet", + "operationId" : "placeOrder", + "requestBody" : { + "description" : "order placed for purchasing the pet", + "content" : { + "*/*" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "required" : true + }, + "responses" : { + "200" : { + "description" : "successful operation", + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + } + }, + "400" : { + "description" : "Invalid Order", + "content" : { } + } + } + } + }, + "/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", + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of pet that needs to be fetched", + "required" : true, + "schema" : { + "maximum" : 5, + "minimum" : 1, + "type" : "integer", + "format" : "int64" + } + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + } + }, + "400" : { + "description" : "Invalid ID supplied", + "content" : { } + }, + "404" : { + "description" : "Order not found", + "content" : { } + } + } + }, + "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", + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of the order that needs to be deleted", + "required" : true, + "schema" : { + "type" : "string" + } + } ], + "responses" : { + "400" : { + "description" : "Invalid ID supplied", + "content" : { } + }, + "404" : { + "description" : "Order not found", + "content" : { } + } + } + } + }, + "/user" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Create user", + "description" : "This can only be done by the logged in user.", + "operationId" : "createUser", + "requestBody" : { + "description" : "Created user object", + "content" : { + "*/*" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "required" : true + }, + "responses" : { + "default" : { + "description" : "successful operation", + "content" : { } + } + } + } + }, + "/user/createWithArray" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Creates list of users with given input array", + "operationId" : "createUsersWithArrayInput", + "requestBody" : { + "description" : "List of user object", + "content" : { + "*/*" : { + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/components/schemas/User" + } + } + } + }, + "required" : true + }, + "responses" : { + "default" : { + "description" : "successful operation", + "content" : { } + } + } + } + }, + "/user/createWithList" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Creates list of users with given input array", + "operationId" : "createUsersWithListInput", + "requestBody" : { + "description" : "List of user object", + "content" : { + "*/*" : { + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/components/schemas/User" + } + } + } + }, + "required" : true + }, + "responses" : { + "default" : { + "description" : "successful operation", + "content" : { } + } + } + } + }, + "/user/login" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Logs user into the system", + "operationId" : "loginUser", + "parameters" : [ { + "name" : "username", + "in" : "query", + "description" : "The user name for login", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "password", + "in" : "query", + "description" : "The password for login in clear text", + "required" : true, + "schema" : { + "type" : "string" + } + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "headers" : { + "X-Rate-Limit" : { + "description" : "calls per hour allowed by the user", + "schema" : { + "type" : "integer", + "format" : "int32" + } + }, + "X-Expires-After" : { + "description" : "date in UTC when toekn expires", + "schema" : { + "type" : "string", + "format" : "date-time" + } + } + }, + "content" : { + "application/xml" : { + "schema" : { + "type" : "string" + } + }, + "application/json" : { + "schema" : { + "type" : "string" + } + } + } + }, + "400" : { + "description" : "Invalid username/password supplied", + "content" : { } + } + } + } + }, + "/user/logout" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Logs out current logged in user session", + "operationId" : "logoutUser", + "responses" : { + "default" : { + "description" : "successful operation", + "content" : { } + } + } + } + }, + "/user/{username}" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Get user by user name", + "operationId" : "getUserByName", + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "The name that needs to be fetched. Use user1 for testing.", + "required" : true, + "schema" : { + "type" : "string" + } + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + } + }, + "400" : { + "description" : "Invalid username supplied", + "content" : { } + }, + "404" : { + "description" : "User not found", + "content" : { } + } + } + }, + "put" : { + "tags" : [ "user" ], + "summary" : "Updated user", + "description" : "This can only be done by the logged in user.", + "operationId" : "updateUser", + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "name that need to be deleted", + "required" : true, + "schema" : { + "type" : "string" + } + } ], + "requestBody" : { + "description" : "Updated user object", + "content" : { + "*/*" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "required" : true + }, + "responses" : { + "400" : { + "description" : "Invalid user supplied", + "content" : { } + }, + "404" : { + "description" : "User not found", + "content" : { } + } + } + }, + "delete" : { + "tags" : [ "user" ], + "summary" : "Delete user", + "description" : "This can only be done by the logged in user.", + "operationId" : "deleteUser", + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "The name that needs to be deleted", + "required" : true, + "schema" : { + "type" : "string" + } + } ], + "responses" : { + "400" : { + "description" : "Invalid username supplied", + "content" : { } + }, + "404" : { + "description" : "User not found", + "content" : { } + } + } + } + } + }, + "components" : { + "schemas" : { + "Order" : { + "title" : "Pet Order", + "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 + } + }, + "description" : "An order for a pets from the pet store", + "example" : { + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" + }, + "xml" : { + "name" : "Order" + } + }, + "Category" : { + "title" : "Pet category", + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "description" : "A category for a pet", + "example" : { + "name" : "name", + "id" : 6 + }, + "xml" : { + "name" : "Category" + } + }, + "User" : { + "title" : "a User", + "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", + "description" : "User Status", + "format" : "int32" + } + }, + "description" : "A User who is purchasing from the pet store", + "example" : { + "firstName" : "firstName", + "lastName" : "lastName", + "password" : "password", + "userStatus" : 6, + "phone" : "phone", + "id" : 0, + "email" : "email", + "username" : "username" + }, + "xml" : { + "name" : "User" + } + }, + "Tag" : { + "title" : "Pet Tag", + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "description" : "A tag for a pet", + "example" : { + "name" : "name", + "id" : 1 + }, + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "title" : "a Pet", + "required" : [ "name", "photoUrls" ], + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "category" : { + "$ref" : "#/components/schemas/Category" + }, + "name" : { + "type" : "string", + "example" : "doggie" + }, + "photoUrls" : { + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + }, + "items" : { + "type" : "string" + } + }, + "tags" : { + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + }, + "items" : { + "$ref" : "#/components/schemas/Tag" + } + }, + "status" : { + "type" : "string", + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ] + } + }, + "description" : "A pet for sale in the pet store", + "example" : { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" + }, + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "title" : "An uploaded response", + "type" : "object", + "properties" : { + "code" : { + "type" : "integer", + "format" : "int32" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + }, + "description" : "Describes the result of uploading an image resource", + "example" : { + "code" : 0, + "type" : "type", + "message" : "message" + } + } + }, + "securitySchemes" : { + "petstore_auth" : { + "type" : "oauth2", + "flows" : { + "implicit" : { + "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", + "scopes" : { + "write:pets" : "modify pets in your account", + "read:pets" : "read your pets" + } + } + } + }, + "api_key" : { + "type" : "apiKey", + "name" : "api_key", + "in" : "header" + } + } + } +} diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/wwwroot/swagger-original.json b/samples/server/petstore/aspnetcore/src/IO.Swagger/wwwroot/swagger-original.json index 723ce2eb47a6..d43d131d4de3 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/wwwroot/swagger-original.json +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/wwwroot/swagger-original.json @@ -563,7 +563,7 @@ "parameters" : [ { "name" : "username", "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing. ", + "description" : "The name that needs to be fetched. Use user1 for testing.", "required" : true, "type" : "string" } ], diff --git a/samples/server/petstore/flaskConnexion/.swagger-codegen/VERSION b/samples/server/petstore/flaskConnexion/.swagger-codegen/VERSION index f9f7450d1359..096bf47efe31 100644 --- a/samples/server/petstore/flaskConnexion/.swagger-codegen/VERSION +++ b/samples/server/petstore/flaskConnexion/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/flaskConnexion/README.md b/samples/server/petstore/flaskConnexion/README.md index 000d12df5829..f623a2a02d8e 100644 --- a/samples/server/petstore/flaskConnexion/README.md +++ b/samples/server/petstore/flaskConnexion/README.md @@ -27,7 +27,7 @@ http://localhost:8080/v2/ui/ Your Swagger definition lives here: ``` -http://localhost:8080/v2/swagger.json +http://localhost:8080/v2/openapi.json ``` To launch the integration tests, use tox: diff --git a/samples/server/petstore/flaskConnexion/setup.py b/samples/server/petstore/flaskConnexion/setup.py index be5dce52ab74..a7f6ac9e413a 100644 --- a/samples/server/petstore/flaskConnexion/setup.py +++ b/samples/server/petstore/flaskConnexion/setup.py @@ -21,10 +21,10 @@ description="Swagger Petstore", author_email="apiteam@swagger.io", url="", - keywords=["Swagger", "Swagger Petstore"], + keywords=["OpenAPI", "Swagger Petstore"], install_requires=REQUIRES, packages=find_packages(), - package_data={'': ['swagger/swagger.yaml']}, + package_data={'': ['openapi/openapi.yaml']}, include_package_data=True, entry_points={ 'console_scripts': ['swagger_server=swagger_server.__main__:main']}, diff --git a/samples/server/petstore/flaskConnexion/swagger_server/__main__.py b/samples/server/petstore/flaskConnexion/swagger_server/__main__.py index 734cc4b3dd21..a2a4e9b03110 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/__main__.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/__main__.py @@ -6,9 +6,9 @@ def main(): - app = connexion.App(__name__, specification_dir='./swagger/') + app = connexion.App(__name__, specification_dir='./openapi/') app.app.json_encoder = encoder.JSONEncoder - app.add_api('swagger.yaml', arguments={'title': 'Swagger Petstore'}) + app.add_api('openapi.yaml', arguments={'title': 'Swagger Petstore'}) app.run(port=8080) diff --git a/samples/server/petstore/flaskConnexion/swagger_server/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/controllers/pet_controller.py index 5de865c908a6..adedc37e1c85 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/controllers/pet_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/controllers/pet_controller.py @@ -6,28 +6,28 @@ from swagger_server import util -def add_pet(body): # noqa: E501 +def add_pet(pet): # noqa: E501 """Add a new pet to the store # noqa: E501 - :param body: Pet object that needs to be added to the store - :type body: dict | bytes + :param pet: Pet object that needs to be added to the store + :type pet: dict | bytes :rtype: None """ if connexion.request.is_json: - body = Pet.from_dict(connexion.request.get_json()) # noqa: E501 + pet = Pet.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' -def delete_pet(petId, api_key=None): # noqa: E501 +def delete_pet(pet_id, api_key=None): # noqa: E501 """Deletes a pet # noqa: E501 - :param petId: Pet id to delete - :type petId: int + :param pet_id: Pet id to delete + :type pet_id: int :param api_key: :type api_key: str @@ -62,41 +62,41 @@ def find_pets_by_tags(tags): # noqa: E501 return 'do some magic!' -def get_pet_by_id(petId): # noqa: E501 +def get_pet_by_id(pet_id): # noqa: E501 """Find pet by ID Returns a single pet # noqa: E501 - :param petId: ID of pet to return - :type petId: int + :param pet_id: ID of pet to return + :type pet_id: int :rtype: Pet """ return 'do some magic!' -def update_pet(body): # noqa: E501 +def update_pet(pet): # noqa: E501 """Update an existing pet # noqa: E501 - :param body: Pet object that needs to be added to the store - :type body: dict | bytes + :param pet: Pet object that needs to be added to the store + :type pet: dict | bytes :rtype: None """ if connexion.request.is_json: - body = Pet.from_dict(connexion.request.get_json()) # noqa: E501 + pet = Pet.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' -def update_pet_with_form(petId, name=None, status=None): # noqa: E501 +def update_pet_with_form(pet_id, name=None, status=None): # noqa: E501 """Updates a pet in the store with form data # noqa: E501 - :param petId: ID of pet that needs to be updated - :type petId: int + :param pet_id: ID of pet that needs to be updated + :type pet_id: int :param name: Updated name of the pet :type name: str :param status: Updated status of the pet @@ -107,17 +107,17 @@ def update_pet_with_form(petId, name=None, status=None): # noqa: E501 return 'do some magic!' -def upload_file(petId, additionalMetadata=None, file=None): # noqa: E501 +def upload_file(pet_id, additional_metadata=None, file=None): # noqa: E501 """uploads an image # noqa: E501 - :param petId: ID of pet to update - :type petId: int - :param additionalMetadata: Additional data to pass to server - :type additionalMetadata: str + :param pet_id: ID of pet to update + :type pet_id: int + :param additional_metadata: Additional data to pass to server + :type additional_metadata: str :param file: file to upload - :type file: werkzeug.datastructures.FileStorage + :type file: str :rtype: ApiResponse """ diff --git a/samples/server/petstore/flaskConnexion/swagger_server/controllers/store_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/controllers/store_controller.py index eae3546c21ed..80c005edc0dc 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/controllers/store_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/controllers/store_controller.py @@ -5,13 +5,13 @@ from swagger_server import util -def delete_order(orderId): # noqa: E501 +def delete_order(order_id): # noqa: E501 """Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 - :param orderId: ID of the order that needs to be deleted - :type orderId: str + :param order_id: ID of the order that needs to be deleted + :type order_id: str :rtype: None """ @@ -29,29 +29,29 @@ def get_inventory(): # noqa: E501 return 'do some magic!' -def get_order_by_id(orderId): # noqa: E501 +def get_order_by_id(order_id): # noqa: E501 """Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 - :param orderId: ID of pet that needs to be fetched - :type orderId: int + :param order_id: ID of pet that needs to be fetched + :type order_id: int :rtype: Order """ return 'do some magic!' -def place_order(body): # noqa: E501 +def place_order(order): # noqa: E501 """Place an order for a pet # noqa: E501 - :param body: order placed for purchasing the pet - :type body: dict | bytes + :param order: order placed for purchasing the pet + :type order: dict | bytes :rtype: Order """ if connexion.request.is_json: - body = Order.from_dict(connexion.request.get_json()) # noqa: E501 + order = Order.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/swagger_server/controllers/user_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/controllers/user_controller.py index c7c3ee3519ab..48cddf17a4f2 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/controllers/user_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/controllers/user_controller.py @@ -5,48 +5,48 @@ from swagger_server import util -def create_user(body): # noqa: E501 +def create_user(user): # noqa: E501 """Create user This can only be done by the logged in user. # noqa: E501 - :param body: Created user object - :type body: dict | bytes + :param user: Created user object + :type user: dict | bytes :rtype: None """ if connexion.request.is_json: - body = User.from_dict(connexion.request.get_json()) # noqa: E501 + user = User.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' -def create_users_with_array_input(body): # noqa: E501 +def create_users_with_array_input(user): # noqa: E501 """Creates list of users with given input array # noqa: E501 - :param body: List of user object - :type body: list | bytes + :param user: List of user object + :type user: list | bytes :rtype: None """ if connexion.request.is_json: - body = [User.from_dict(d) for d in connexion.request.get_json()] # noqa: E501 + user = [User.from_dict(d) for d in connexion.request.get_json()] # noqa: E501 return 'do some magic!' -def create_users_with_list_input(body): # noqa: E501 +def create_users_with_list_input(user): # noqa: E501 """Creates list of users with given input array # noqa: E501 - :param body: List of user object - :type body: list | bytes + :param user: List of user object + :type user: list | bytes :rtype: None """ if connexion.request.is_json: - body = [User.from_dict(d) for d in connexion.request.get_json()] # noqa: E501 + user = [User.from_dict(d) for d in connexion.request.get_json()] # noqa: E501 return 'do some magic!' @@ -68,7 +68,7 @@ def get_user_by_name(username): # noqa: E501 # noqa: E501 - :param username: The name that needs to be fetched. Use user1 for testing. + :param username: The name that needs to be fetched. Use user1 for testing. :type username: str :rtype: User @@ -102,18 +102,18 @@ def logout_user(): # noqa: E501 return 'do some magic!' -def update_user(username, body): # noqa: E501 +def update_user(username, user): # noqa: E501 """Updated user This can only be done by the logged in user. # noqa: E501 :param username: name that need to be deleted :type username: str - :param body: Updated user object - :type body: dict | bytes + :param user: Updated user object + :type user: dict | bytes :rtype: None """ if connexion.request.is_json: - body = User.from_dict(connexion.request.get_json()) # noqa: E501 + user = User.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/swagger_server/openapi/openapi.yaml b/samples/server/petstore/flaskConnexion/swagger_server/openapi/openapi.yaml new file mode 100644 index 000000000000..89e8be270584 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/swagger_server/openapi/openapi.yaml @@ -0,0 +1,742 @@ +openapi: 3.0.1 +info: + title: Swagger Petstore + description: 'This is a sample server Petstore server. You can find out more about + Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For + this sample, you can use the api key `special-key` to test the authorization filters.' + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache-2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.0 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: +- url: http://petstore.swagger.io/v2 +tags: +- name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io +- name: store + description: Access to Petstore orders +- name: user + description: Operations about user + externalDocs: + description: Find out more about our store + url: http://swagger.io +paths: + /pet: + put: + tags: + - pet + summary: Update an existing pet + operationId: update_pet + requestBody: + description: Pet object that needs to be added to the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + 400: + description: Invalid ID supplied + content: {} + 404: + description: Pet not found + content: {} + 405: + description: Validation exception + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + x-swagger-router-controller: swagger_server.controllers.pet_controller + post: + tags: + - pet + summary: Add a new pet to the store + operationId: add_pet + requestBody: + description: Pet object that needs to be added to the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + 405: + description: Invalid input + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + x-swagger-router-controller: swagger_server.controllers.pet_controller + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: find_pets_by_status + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + explode: false + schema: + type: array + items: + type: string + default: available + enum: + - available + - pending + - sold + responses: + 200: + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + 400: + description: Invalid status value + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + x-swagger-router-controller: swagger_server.controllers.pet_controller + /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: find_pets_by_tags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + explode: false + schema: + type: array + items: + type: string + responses: + 200: + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + 400: + description: Invalid tag value + content: {} + deprecated: true + security: + - petstore_auth: + - write:pets + - read:pets + x-swagger-router-controller: swagger_server.controllers.pet_controller + /pet/{petId}: + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: get_pet_by_id + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + 400: + description: Invalid ID supplied + content: {} + 404: + description: Pet not found + content: {} + security: + - api_key: [] + x-swagger-router-controller: swagger_server.controllers.pet_controller + post: + tags: + - pet + summary: Updates a pet in the store with form data + operationId: update_pet_with_form + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + requestBody: + content: + application/x-www-form-urlencoded: + schema: + properties: + name: + type: string + description: Updated name of the pet + status: + type: string + description: Updated status of the pet + responses: + 405: + description: Invalid input + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + x-swagger-router-controller: swagger_server.controllers.pet_controller + delete: + tags: + - pet + summary: Deletes a pet + operationId: delete_pet + parameters: + - name: api_key + in: header + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + 400: + description: Invalid pet value + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + x-swagger-router-controller: swagger_server.controllers.pet_controller + /pet/{petId}/uploadImage: + post: + tags: + - pet + summary: uploads an image + operationId: upload_file + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + requestBody: + content: + multipart/form-data: + schema: + properties: + additionalMetadata: + type: string + description: Additional data to pass to server + file: + type: string + description: file to upload + format: binary + responses: + 200: + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - write:pets + - read:pets + x-swagger-router-controller: swagger_server.controllers.pet_controller + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: get_inventory + responses: + 200: + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + x-swagger-router-controller: swagger_server.controllers.store_controller + /store/order: + post: + tags: + - store + summary: Place an order for a pet + operationId: place_order + requestBody: + description: order placed for purchasing the pet + content: + '*/*': + schema: + $ref: '#/components/schemas/Order' + required: true + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + 400: + description: Invalid Order + content: {} + x-swagger-router-controller: swagger_server.controllers.store_controller + /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: get_order_by_id + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + maximum: 5 + minimum: 1 + type: integer + format: int64 + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + 400: + description: Invalid ID supplied + content: {} + 404: + description: Order not found + content: {} + x-swagger-router-controller: swagger_server.controllers.store_controller + 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: delete_order + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + 400: + description: Invalid ID supplied + content: {} + 404: + description: Order not found + content: {} + x-swagger-router-controller: swagger_server.controllers.store_controller + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: create_user + requestBody: + description: Created user object + content: + '*/*': + schema: + $ref: '#/components/schemas/User' + required: true + responses: + default: + description: successful operation + content: {} + x-swagger-router-controller: swagger_server.controllers.user_controller + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + operationId: create_users_with_array_input + requestBody: + description: List of user object + content: + '*/*': + schema: + type: array + items: + $ref: '#/components/schemas/User' + required: true + responses: + default: + description: successful operation + content: {} + x-swagger-router-controller: swagger_server.controllers.user_controller + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + operationId: create_users_with_list_input + requestBody: + description: List of user object + content: + '*/*': + schema: + type: array + items: + $ref: '#/components/schemas/User' + required: true + responses: + default: + description: successful operation + content: {} + x-swagger-router-controller: swagger_server.controllers.user_controller + /user/login: + get: + tags: + - user + summary: Logs user into the system + operationId: login_user + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + 200: + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when toekn expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + 400: + description: Invalid username/password supplied + content: {} + x-swagger-router-controller: swagger_server.controllers.user_controller + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + operationId: logout_user + responses: + default: + description: successful operation + content: {} + x-swagger-router-controller: swagger_server.controllers.user_controller + /user/{username}: + get: + tags: + - user + summary: Get user by user name + operationId: get_user_by_name + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + 400: + description: Invalid username supplied + content: {} + 404: + description: User not found + content: {} + x-swagger-router-controller: swagger_server.controllers.user_controller + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: update_user + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + requestBody: + description: Updated user object + content: + '*/*': + schema: + $ref: '#/components/schemas/User' + required: true + responses: + 400: + description: Invalid user supplied + content: {} + 404: + description: User not found + content: {} + x-swagger-router-controller: swagger_server.controllers.user_controller + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: delete_user + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + 400: + description: Invalid username supplied + content: {} + 404: + description: User not found + content: {} + x-swagger-router-controller: swagger_server.controllers.user_controller +components: + schemas: + Order: + title: Pet Order + 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 + description: An order for a pets from the pet store + xml: + name: Order + Category: + title: Pet category + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + description: A category for a pet + xml: + name: Category + User: + title: a User + 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 + description: User Status + format: int32 + description: A User who is purchasing from the pet store + xml: + name: User + Tag: + title: Pet Tag + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + description: A tag for a pet + xml: + name: Tag + Pet: + title: a Pet + required: + - name + - photoUrls + type: object + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + description: A pet for sale in the pet store + xml: + name: Pet + ApiResponse: + title: An uploaded response + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + description: Describes the result of uploading an image resource + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + api_key: + type: apiKey + name: api_key + in: header diff --git a/samples/server/petstore/flaskConnexion/swagger_server/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion/swagger_server/swagger/swagger.yaml deleted file mode 100644 index 836d533de5ca..000000000000 --- a/samples/server/petstore/flaskConnexion/swagger_server/swagger/swagger.yaml +++ /dev/null @@ -1,775 +0,0 @@ ---- -swagger: "2.0" -info: - description: "This is a sample server Petstore server. You can find out more about\ - \ Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).\ - \ For this sample, you can use the api key `special-key` to test the authorization\ - \ filters." - version: "1.0.0" - title: "Swagger Petstore" - termsOfService: "http://swagger.io/terms/" - contact: - email: "apiteam@swagger.io" - 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" - externalDocs: - description: "Find out more" - url: "http://swagger.io" -- name: "store" - description: "Access to Petstore orders" -- name: "user" - description: "Operations about user" - externalDocs: - description: "Find out more about our store" - url: "http://swagger.io" -schemes: -- "http" -paths: - /pet: - post: - tags: - - "pet" - summary: "Add a new pet to the store" - description: "" - operationId: "add_pet" - 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" - x-swagger-router-controller: "swagger_server.controllers.pet_controller" - put: - tags: - - "pet" - summary: "Update an existing pet" - description: "" - operationId: "update_pet" - 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" - x-swagger-router-controller: "swagger_server.controllers.pet_controller" - /pet/findByStatus: - get: - tags: - - "pet" - summary: "Finds Pets by status" - description: "Multiple status values can be provided with comma separated strings" - operationId: "find_pets_by_status" - 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" - default: "available" - enum: - - "available" - - "pending" - - "sold" - 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" - x-swagger-router-controller: "swagger_server.controllers.pet_controller" - /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: "find_pets_by_tags" - 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 - x-swagger-router-controller: "swagger_server.controllers.pet_controller" - /pet/{petId}: - get: - tags: - - "pet" - summary: "Find pet by ID" - description: "Returns a single pet" - operationId: "get_pet_by_id" - 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: [] - x-swagger-router-controller: "swagger_server.controllers.pet_controller" - post: - tags: - - "pet" - summary: "Updates a pet in the store with form data" - description: "" - operationId: "update_pet_with_form" - 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" - - 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" - responses: - 405: - description: "Invalid input" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - x-swagger-router-controller: "swagger_server.controllers.pet_controller" - delete: - tags: - - "pet" - summary: "Deletes a pet" - description: "" - operationId: "delete_pet" - 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" - x-swagger-router-controller: "swagger_server.controllers.pet_controller" - /pet/{petId}/uploadImage: - post: - tags: - - "pet" - summary: "uploads an image" - description: "" - operationId: "upload_file" - 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" - x-swagger-router-controller: "swagger_server.controllers.pet_controller" - /store/inventory: - get: - tags: - - "store" - summary: "Returns pet inventories by status" - description: "Returns a map of status codes to quantities" - operationId: "get_inventory" - produces: - - "application/json" - parameters: [] - responses: - 200: - description: "successful operation" - schema: - type: "object" - additionalProperties: - type: "integer" - format: "int32" - security: - - api_key: [] - x-swagger-router-controller: "swagger_server.controllers.store_controller" - /store/order: - post: - tags: - - "store" - summary: "Place an order for a pet" - description: "" - operationId: "place_order" - 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" - x-swagger-router-controller: "swagger_server.controllers.store_controller" - /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: "get_order_by_id" - 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" - x-swagger-router-controller: "swagger_server.controllers.store_controller" - 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: "delete_order" - 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" - x-swagger-router-controller: "swagger_server.controllers.store_controller" - /user: - post: - tags: - - "user" - summary: "Create user" - description: "This can only be done by the logged in user." - operationId: "create_user" - 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" - x-swagger-router-controller: "swagger_server.controllers.user_controller" - /user/createWithArray: - post: - tags: - - "user" - summary: "Creates list of users with given input array" - description: "" - operationId: "create_users_with_array_input" - 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" - x-swagger-router-controller: "swagger_server.controllers.user_controller" - /user/createWithList: - post: - tags: - - "user" - summary: "Creates list of users with given input array" - description: "" - operationId: "create_users_with_list_input" - 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" - x-swagger-router-controller: "swagger_server.controllers.user_controller" - /user/login: - get: - tags: - - "user" - summary: "Logs user into the system" - description: "" - operationId: "login_user" - 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" - x-swagger-router-controller: "swagger_server.controllers.user_controller" - /user/logout: - get: - tags: - - "user" - summary: "Logs out current logged in user session" - description: "" - operationId: "logout_user" - produces: - - "application/xml" - - "application/json" - parameters: [] - responses: - default: - description: "successful operation" - x-swagger-router-controller: "swagger_server.controllers.user_controller" - /user/{username}: - get: - tags: - - "user" - summary: "Get user by user name" - description: "" - operationId: "get_user_by_name" - 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" - x-swagger-router-controller: "swagger_server.controllers.user_controller" - put: - tags: - - "user" - summary: "Updated user" - description: "This can only be done by the logged in user." - operationId: "update_user" - 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" - x-swagger-router-controller: "swagger_server.controllers.user_controller" - delete: - tags: - - "user" - summary: "Delete user" - description: "This can only be done by the logged in user." - operationId: "delete_user" - 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" - x-swagger-router-controller: "swagger_server.controllers.user_controller" -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: - 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 - title: "Pet Order" - description: "An order for a pets from the pet store" - example: - petId: 6 - quantity: 1 - id: 0 - shipDate: "2000-01-23T04:56:07.000+00:00" - complete: false - status: "placed" - xml: - name: "Order" - Category: - type: "object" - properties: - id: - type: "integer" - format: "int64" - name: - type: "string" - title: "Pet category" - description: "A category for a pet" - example: - name: "name" - id: 6 - xml: - name: "Category" - User: - 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" - title: "a User" - description: "A User who is purchasing from the pet store" - example: - firstName: "firstName" - lastName: "lastName" - password: "password" - userStatus: 6 - phone: "phone" - id: 0 - email: "email" - username: "username" - xml: - name: "User" - Tag: - type: "object" - properties: - id: - type: "integer" - format: "int64" - name: - type: "string" - title: "Pet Tag" - description: "A tag for a pet" - example: - name: "name" - id: 1 - xml: - name: "Tag" - Pet: - type: "object" - required: - - "name" - - "photoUrls" - properties: - id: - type: "integer" - format: "int64" - category: - $ref: "#/definitions/Category" - name: - type: "string" - example: "doggie" - photoUrls: - type: "array" - xml: - name: "photoUrl" - wrapped: true - items: - type: "string" - tags: - type: "array" - xml: - name: "tag" - wrapped: true - items: - $ref: "#/definitions/Tag" - status: - type: "string" - description: "pet status in the store" - enum: - - "available" - - "pending" - - "sold" - title: "a Pet" - description: "A pet for sale in the pet store" - example: - photoUrls: - - "photoUrls" - - "photoUrls" - name: "doggie" - id: 0 - category: - name: "name" - id: 6 - tags: - - name: "name" - id: 1 - - name: "name" - id: 1 - status: "available" - xml: - name: "Pet" - ApiResponse: - type: "object" - properties: - code: - type: "integer" - format: "int32" - type: - type: "string" - message: - type: "string" - title: "An uploaded response" - description: "Describes the result of uploading an image resource" - example: - code: 0 - type: "type" - message: "message" -externalDocs: - description: "Find out more about Swagger" - url: "http://swagger.io" diff --git a/samples/server/petstore/flaskConnexion/swagger_server/test/__init__.py b/samples/server/petstore/flaskConnexion/swagger_server/test/__init__.py index 644506301ce0..60caf919dd1b 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/test/__init__.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/__init__.py @@ -10,7 +10,7 @@ class BaseTestCase(TestCase): def create_app(self): logging.getLogger('connexion.operation').setLevel('ERROR') - app = connexion.App(__name__, specification_dir='../swagger/') + app = connexion.App(__name__, specification_dir='../openapi/') app.app.json_encoder = JSONEncoder - app.add_api('swagger.yaml') + app.add_api('openapi.yaml') return app.app diff --git a/samples/server/petstore/flaskConnexion/swagger_server/test/test_pet_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/test/test_pet_controller.py index fb4c34ea3e10..48420a9235a6 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/test/test_pet_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/test_pet_controller.py @@ -18,11 +18,11 @@ def test_add_pet(self): Add a new pet to the store """ - body = Pet() + pet = Pet() response = self.client.open( '/v2/pet', method='POST', - data=json.dumps(body), + data=json.dumps(pet), content_type='application/json') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) @@ -34,7 +34,7 @@ def test_delete_pet(self): """ headers = [('api_key', 'api_key_example')] response = self.client.open( - '/v2/pet/{petId}'.format(petId=789), + '/v2/pet/{petId}'.format(pet_id=789), method='DELETE', headers=headers) self.assert200(response, @@ -72,7 +72,7 @@ def test_get_pet_by_id(self): Find pet by ID """ response = self.client.open( - '/v2/pet/{petId}'.format(petId=789), + '/v2/pet/{petId}'.format(pet_id=789), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) @@ -82,11 +82,11 @@ def test_update_pet(self): Update an existing pet """ - body = Pet() + pet = Pet() response = self.client.open( '/v2/pet', method='PUT', - data=json.dumps(body), + data=json.dumps(pet), content_type='application/json') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) @@ -99,7 +99,7 @@ def test_update_pet_with_form(self): data = dict(name='name_example', status='status_example') response = self.client.open( - '/v2/pet/{petId}'.format(petId=789), + '/v2/pet/{petId}'.format(pet_id=789), method='POST', data=data, content_type='application/x-www-form-urlencoded') @@ -111,10 +111,10 @@ def test_upload_file(self): uploads an image """ - data = dict(additionalMetadata='additionalMetadata_example', + data = dict(additional_metadata='additional_metadata_example', file=(BytesIO(b'some file data'), 'file.txt')) response = self.client.open( - '/v2/pet/{petId}/uploadImage'.format(petId=789), + '/v2/pet/{petId}/uploadImage'.format(pet_id=789), method='POST', data=data, content_type='multipart/form-data') diff --git a/samples/server/petstore/flaskConnexion/swagger_server/test/test_store_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/test/test_store_controller.py index 854e18600fc3..0b51797541c8 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/test/test_store_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/test_store_controller.py @@ -18,7 +18,7 @@ def test_delete_order(self): Delete purchase order by ID """ response = self.client.open( - '/v2/store/order/{orderId}'.format(orderId='orderId_example'), + '/v2/store/order/{orderId}'.format(order_id='order_id_example'), method='DELETE') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) @@ -40,7 +40,7 @@ def test_get_order_by_id(self): Find purchase order by ID """ response = self.client.open( - '/v2/store/order/{orderId}'.format(orderId=5), + '/v2/store/order/{orderId}'.format(order_id=5), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) @@ -50,12 +50,12 @@ def test_place_order(self): Place an order for a pet """ - body = Order() + order = Order() response = self.client.open( '/v2/store/order', method='POST', - data=json.dumps(body), - content_type='application/json') + data=json.dumps(order), + content_type='*/*') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) diff --git a/samples/server/petstore/flaskConnexion/swagger_server/test/test_user_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/test/test_user_controller.py index 30e1885afabf..10696f43607e 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/test/test_user_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/test_user_controller.py @@ -17,12 +17,12 @@ def test_create_user(self): Create user """ - body = User() + user = User() response = self.client.open( '/v2/user', method='POST', - data=json.dumps(body), - content_type='application/json') + data=json.dumps(user), + content_type='*/*') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) @@ -31,12 +31,12 @@ def test_create_users_with_array_input(self): Creates list of users with given input array """ - body = [User()] + user = [User()] response = self.client.open( '/v2/user/createWithArray', method='POST', - data=json.dumps(body), - content_type='application/json') + data=json.dumps(user), + content_type='*/*') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) @@ -45,12 +45,12 @@ def test_create_users_with_list_input(self): Creates list of users with given input array """ - body = [User()] + user = [User()] response = self.client.open( '/v2/user/createWithList', method='POST', - data=json.dumps(body), - content_type='application/json') + data=json.dumps(user), + content_type='*/*') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) @@ -106,12 +106,12 @@ def test_update_user(self): Updated user """ - body = User() + user = User() response = self.client.open( '/v2/user/{username}'.format(username='username_example'), method='PUT', - data=json.dumps(body), - content_type='application/json') + data=json.dumps(user), + content_type='*/*') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) diff --git a/samples/server/petstore/java-play-framework-async/.swagger-codegen-ignore b/samples/server/petstore/java-play-framework-async/.swagger-codegen-ignore new file mode 100644 index 000000000000..c5fa491b4c55 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/java-play-framework-async/.swagger-codegen/VERSION b/samples/server/petstore/java-play-framework-async/.swagger-codegen/VERSION new file mode 100644 index 000000000000..855ff9501eb8 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-async/LICENSE b/samples/server/petstore/java-play-framework-async/LICENSE new file mode 100644 index 000000000000..4baedcb95f3d --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/LICENSE @@ -0,0 +1,8 @@ +This software is licensed under the Apache 2 license, quoted below. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project 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. \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-async/README b/samples/server/petstore/java-play-framework-async/README new file mode 100644 index 000000000000..2fce02950d27 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/README @@ -0,0 +1,4 @@ +This is your new Play application +================================= + +This file will be packaged with your application when using `activator dist`. \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-async/app/Module.java b/samples/server/petstore/java-play-framework-async/app/Module.java new file mode 100644 index 000000000000..f1b062c29345 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/Module.java @@ -0,0 +1,13 @@ +import com.google.inject.AbstractModule; + +import controllers.*; + +public class Module extends AbstractModule { + + @Override + protected void configure() { + bind(PetApiControllerImpInterface.class).to(PetApiControllerImp.class); + bind(StoreApiControllerImpInterface.class).to(StoreApiControllerImp.class); + bind(UserApiControllerImpInterface.class).to(UserApiControllerImp.class); + } +} \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-async/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-async/app/apimodels/Category.java new file mode 100644 index 000000000000..9f0206575f5c --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/Category.java @@ -0,0 +1,96 @@ +package apimodels; + +import com.fasterxml.jackson.annotation.*; +import java.util.Set; +import javax.validation.*; +import java.util.Objects; +import javax.validation.constraints.*; +/** + * A category for a pet + */ + +@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) +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 + **/ + 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 + **/ + 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(id, category.id) && + Objects.equals(name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @SuppressWarnings("StringBufferReplaceableByString") + @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/server/petstore/java-play-framework-async/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-async/app/apimodels/ModelApiResponse.java new file mode 100644 index 000000000000..07493e848250 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/ModelApiResponse.java @@ -0,0 +1,118 @@ +package apimodels; + +import com.fasterxml.jackson.annotation.*; +import java.util.Set; +import javax.validation.*; +import java.util.Objects; +import javax.validation.constraints.*; +/** + * Describes the result of uploading an image resource + */ + +@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) +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 + **/ + 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 + **/ + 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 + **/ + 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(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @SuppressWarnings("StringBufferReplaceableByString") + @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/server/petstore/java-play-framework-async/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-async/app/apimodels/Order.java new file mode 100644 index 000000000000..cdc21f722c9c --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/Order.java @@ -0,0 +1,219 @@ +package apimodels; + +import java.time.OffsetDateTime; +import com.fasterxml.jackson.annotation.*; +import java.util.Set; +import javax.validation.*; +import java.util.Objects; +import javax.validation.constraints.*; +/** + * An order for a pets from the pet store + */ + +@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) +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 final String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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; + } + } + return null; + } + } + + @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 + **/ + 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 + **/ + 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 + **/ + 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 + 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 + **/ + 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 + **/ + public Boolean isComplete() { + 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(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @SuppressWarnings("StringBufferReplaceableByString") + @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/server/petstore/java-play-framework-async/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-async/app/apimodels/Pet.java new file mode 100644 index 000000000000..5e5ff3762945 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/Pet.java @@ -0,0 +1,238 @@ +package apimodels; + +import apimodels.Category; +import apimodels.Tag; +import java.util.ArrayList; +import java.util.List; +import com.fasterxml.jackson.annotation.*; +import java.util.Set; +import javax.validation.*; +import java.util.Objects; +import javax.validation.constraints.*; +/** + * A pet for sale in the pet store + */ + +@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) +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 final String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + 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 + 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 + 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) { + photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @NotNull + 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 (tags == null) { + tags = new ArrayList<>(); + } + tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @Valid + 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 + **/ + 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(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @SuppressWarnings("StringBufferReplaceableByString") + @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/server/petstore/java-play-framework-async/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-async/app/apimodels/Tag.java new file mode 100644 index 000000000000..15a8774252af --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/Tag.java @@ -0,0 +1,96 @@ +package apimodels; + +import com.fasterxml.jackson.annotation.*; +import java.util.Set; +import javax.validation.*; +import java.util.Objects; +import javax.validation.constraints.*; +/** + * A tag for a pet + */ + +@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) +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 + **/ + 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 + **/ + 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(id, tag.id) && + Objects.equals(name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @SuppressWarnings("StringBufferReplaceableByString") + @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/server/petstore/java-play-framework-async/app/apimodels/User.java b/samples/server/petstore/java-play-framework-async/app/apimodels/User.java new file mode 100644 index 000000000000..689de768893e --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/User.java @@ -0,0 +1,228 @@ +package apimodels; + +import com.fasterxml.jackson.annotation.*; +import java.util.Set; +import javax.validation.*; +import java.util.Objects; +import javax.validation.constraints.*; +/** + * A User who is purchasing from the pet store + */ + +@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) +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 + **/ + 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 + **/ + 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 + **/ + 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 + **/ + 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 + **/ + 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 + **/ + 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 + **/ + 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 + **/ + 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(id, user.id) && + Objects.equals(username, user.username) && + Objects.equals(firstName, user.firstName) && + Objects.equals(lastName, user.lastName) && + Objects.equals(email, user.email) && + Objects.equals(password, user.password) && + Objects.equals(phone, user.phone) && + Objects.equals(userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @SuppressWarnings("StringBufferReplaceableByString") + @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/server/petstore/java-play-framework-async/app/controllers/ApiDocController.java b/samples/server/petstore/java-play-framework-async/app/controllers/ApiDocController.java new file mode 100644 index 000000000000..53536fd24187 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/controllers/ApiDocController.java @@ -0,0 +1,15 @@ +package controllers; + +import javax.inject.*; +import play.mvc.*; + +public class ApiDocController extends Controller { + + @Inject + private ApiDocController() { + } + + public Result api() { + return redirect("/assets/lib/swagger-ui/index.html?/url=/assets/swagger.json"); + } +} diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiController.java new file mode 100644 index 000000000000..d5ab19462827 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiController.java @@ -0,0 +1,207 @@ +package controllers; + +import java.io.InputStream; +import apimodels.ModelApiResponse; +import apimodels.Pet; + +import play.mvc.Controller; +import play.mvc.Result; +import play.mvc.Http; +import java.util.List; +import java.util.Map; +import java.util.ArrayList; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.google.inject.Inject; +import java.io.File; +import swagger.SwaggerUtils; +import com.fasterxml.jackson.core.type.TypeReference; + +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; + +import javax.validation.constraints.*; +import play.Configuration; + +import swagger.SwaggerUtils.ApiAction; + + +public class PetApiController extends Controller { + + private final PetApiControllerImpInterface imp; + private final ObjectMapper mapper; + private final Configuration configuration; + + @Inject + private PetApiController(Configuration configuration, PetApiControllerImpInterface imp) { + this.imp = imp; + mapper = new ObjectMapper(); + this.configuration = configuration; + } + + + @ApiAction + public CompletionStage addPet() throws Exception { + JsonNode nodebody = request().body().asJson(); + Pet body; + if (nodebody != null) { + body = mapper.readValue(nodebody.toString(), Pet.class); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } + } else { + throw new IllegalArgumentException("'body' parameter is required"); + } + return CompletableFuture.supplyAsync(() -> { + imp.addPet(body) + return ok(); + }); + } + + @ApiAction + public CompletionStage deletePet(Long petId) throws Exception { + String valueapiKey = request().getHeader("api_key"); + String apiKey; + if (valueapiKey != null) { + apiKey = valueapiKey; + } else { + apiKey = null; + } + return CompletableFuture.supplyAsync(() -> { + imp.deletePet(petId, apiKey) + return ok(); + }); + } + + @ApiAction + public CompletionStage findPetsByStatus() throws Exception { + String[] statusArray = request().queryString().get("status"); + if (statusArray == null) { + throw new IllegalArgumentException("'status' parameter is required"); + } + List statusList = SwaggerUtils.parametersToList("csv", statusArray); + List status = new ArrayList(); + for (String curParam : statusList) { + if (!curParam.isEmpty()) { + //noinspection UseBulkOperation + status.add(curParam); + } + } + CompletionStage> stage = imp.findPetsByStatus(status).thenApply(obj -> { + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } + } + return obj; + }); + stage.thenApply(obj -> { + JsonNode result = mapper.valueToTree(obj); + return ok(result); + }); + } + + @ApiAction + public CompletionStage findPetsByTags() throws Exception { + String[] tagsArray = request().queryString().get("tags"); + if (tagsArray == null) { + throw new IllegalArgumentException("'tags' parameter is required"); + } + List tagsList = SwaggerUtils.parametersToList("csv", tagsArray); + List tags = new ArrayList(); + for (String curParam : tagsList) { + if (!curParam.isEmpty()) { + //noinspection UseBulkOperation + tags.add(curParam); + } + } + CompletionStage> stage = imp.findPetsByTags(tags).thenApply(obj -> { + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } + } + return obj; + }); + stage.thenApply(obj -> { + JsonNode result = mapper.valueToTree(obj); + return ok(result); + }); + } + + @ApiAction + public CompletionStage getPetById(Long petId) throws Exception { + CompletionStage stage = imp.getPetById(petId).thenApply(obj -> { + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } + return obj; + }); + stage.thenApply(obj -> { + JsonNode result = mapper.valueToTree(obj); + return ok(result); + }); + } + + @ApiAction + public CompletionStage updatePet() throws Exception { + JsonNode nodebody = request().body().asJson(); + Pet body; + if (nodebody != null) { + body = mapper.readValue(nodebody.toString(), Pet.class); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } + } else { + throw new IllegalArgumentException("'body' parameter is required"); + } + return CompletableFuture.supplyAsync(() -> { + imp.updatePet(body) + return ok(); + }); + } + + @ApiAction + public CompletionStage updatePetWithForm(Long petId) throws Exception { + String valuename = (request().body().asMultipartFormData().asFormUrlEncoded().get("name"))[0]; + String name; + if (valuename != null) { + name = valuename; + } else { + name = null; + } + String valuestatus = (request().body().asMultipartFormData().asFormUrlEncoded().get("status"))[0]; + String status; + if (valuestatus != null) { + status = valuestatus; + } else { + status = null; + } + return CompletableFuture.supplyAsync(() -> { + imp.updatePetWithForm(petId, name, status) + return ok(); + }); + } + + @ApiAction + public CompletionStage uploadFile(Long petId) throws Exception { + String valueadditionalMetadata = (request().body().asMultipartFormData().asFormUrlEncoded().get("additionalMetadata"))[0]; + String additionalMetadata; + if (valueadditionalMetadata != null) { + additionalMetadata = valueadditionalMetadata; + } else { + additionalMetadata = null; + } + Http.MultipartFormData.FilePart file = request().body().asMultipartFormData().getFile("file"); + CompletionStage stage = imp.uploadFile(petId, additionalMetadata, file).thenApply(obj -> { + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } + return obj; + }); + stage.thenApply(obj -> { + JsonNode result = mapper.valueToTree(obj); + return ok(result); + }); + } +} diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImp.java new file mode 100644 index 000000000000..550cb3714350 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImp.java @@ -0,0 +1,67 @@ +package controllers; + +import java.io.InputStream; +import apimodels.ModelApiResponse; +import apimodels.Pet; + +import play.mvc.Http; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.io.FileInputStream; +import javax.validation.constraints.*; + +public class PetApiControllerImp implements PetApiControllerImpInterface { + @Override + public void addPet(Pet body) throws Exception { + //Do your magic!!! + } + + @Override + public void deletePet(Long petId, String apiKey) throws Exception { + //Do your magic!!! + } + + @Override + public CompletionStage> findPetsByStatus( @NotNull List status) throws Exception { + //Do your magic!!! + return CompletableFuture.supplyAsync(() -> { + return new ArrayList(); + }); + } + + @Override + public CompletionStage> findPetsByTags( @NotNull List tags) throws Exception { + //Do your magic!!! + return CompletableFuture.supplyAsync(() -> { + return new ArrayList(); + }); + } + + @Override + public CompletionStage getPetById(Long petId) throws Exception { + //Do your magic!!! + return CompletableFuture.supplyAsync(() -> { + return new Pet(); + }); + } + + @Override + public void updatePet(Pet body) throws Exception { + //Do your magic!!! + } + + @Override + public void updatePetWithForm(Long petId, String name, String status) throws Exception { + //Do your magic!!! + } + + @Override + public CompletionStage uploadFile(Long petId, String additionalMetadata, Http.MultipartFormData.FilePart file) throws Exception { + //Do your magic!!! + return CompletableFuture.supplyAsync(() -> { + return new ModelApiResponse(); + }); + } + +} diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImpInterface.java new file mode 100644 index 000000000000..7e4026b84cbf --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImpInterface.java @@ -0,0 +1,34 @@ +package controllers; + +import java.io.InputStream; +import apimodels.ModelApiResponse; +import apimodels.Pet; + +import play.mvc.Http; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; + +import javax.validation.constraints.*; + +@SuppressWarnings("RedundantThrows") +public interface PetApiControllerImpInterface { + void addPet(Pet body) throws Exception; + + void deletePet(Long petId, String apiKey) throws Exception; + + CompletionStage> findPetsByStatus( @NotNull List status) throws Exception; + + CompletionStage> findPetsByTags( @NotNull List tags) throws Exception; + + CompletionStage getPetById(Long petId) throws Exception; + + void updatePet(Pet body) throws Exception; + + void updatePetWithForm(Long petId, String name, String status) throws Exception; + + CompletionStage uploadFile(Long petId, String additionalMetadata, Http.MultipartFormData.FilePart file) throws Exception; + +} diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiController.java new file mode 100644 index 000000000000..74c34d1fc5e2 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiController.java @@ -0,0 +1,98 @@ +package controllers; + +import java.util.Map; +import apimodels.Order; + +import play.mvc.Controller; +import play.mvc.Result; +import play.mvc.Http; +import java.util.List; +import java.util.Map; +import java.util.ArrayList; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.google.inject.Inject; +import java.io.File; +import swagger.SwaggerUtils; +import com.fasterxml.jackson.core.type.TypeReference; + +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; + +import javax.validation.constraints.*; +import play.Configuration; + +import swagger.SwaggerUtils.ApiAction; + + +public class StoreApiController extends Controller { + + private final StoreApiControllerImpInterface imp; + private final ObjectMapper mapper; + private final Configuration configuration; + + @Inject + private StoreApiController(Configuration configuration, StoreApiControllerImpInterface imp) { + this.imp = imp; + mapper = new ObjectMapper(); + this.configuration = configuration; + } + + + @ApiAction + public CompletionStage deleteOrder(String orderId) throws Exception { + return CompletableFuture.supplyAsync(() -> { + imp.deleteOrder(orderId) + return ok(); + }); + } + + @ApiAction + public CompletionStage getInventory() throws Exception { + CompletionStage> stage = imp.getInventory().thenApply(obj -> { + return obj; + }); + stage.thenApply(obj -> { + JsonNode result = mapper.valueToTree(obj); + return ok(result); + }); + } + + @ApiAction + public CompletionStage getOrderById( @Min(1) @Max(5)Long orderId) throws Exception { + CompletionStage stage = imp.getOrderById(orderId).thenApply(obj -> { + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } + return obj; + }); + stage.thenApply(obj -> { + JsonNode result = mapper.valueToTree(obj); + return ok(result); + }); + } + + @ApiAction + public CompletionStage placeOrder() throws Exception { + JsonNode nodebody = request().body().asJson(); + Order body; + if (nodebody != null) { + body = mapper.readValue(nodebody.toString(), Order.class); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } + } else { + throw new IllegalArgumentException("'body' parameter is required"); + } + CompletionStage stage = imp.placeOrder(body).thenApply(obj -> { + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } + return obj; + }); + stage.thenApply(obj -> { + JsonNode result = mapper.valueToTree(obj); + return ok(result); + }); + } +} diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImp.java new file mode 100644 index 000000000000..2d7cea1cf01a --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImp.java @@ -0,0 +1,43 @@ +package controllers; + +import java.util.Map; +import apimodels.Order; + +import play.mvc.Http; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.io.FileInputStream; +import javax.validation.constraints.*; + +public class StoreApiControllerImp implements StoreApiControllerImpInterface { + @Override + public void deleteOrder(String orderId) throws Exception { + //Do your magic!!! + } + + @Override + public CompletionStage> getInventory() throws Exception { + //Do your magic!!! + return CompletableFuture.supplyAsync(() -> { + return new HashMap(); + }); + } + + @Override + public CompletionStage getOrderById( @Min(1) @Max(5)Long orderId) throws Exception { + //Do your magic!!! + return CompletableFuture.supplyAsync(() -> { + return new Order(); + }); + } + + @Override + public CompletionStage placeOrder(Order body) throws Exception { + //Do your magic!!! + return CompletableFuture.supplyAsync(() -> { + return new Order(); + }); + } + +} diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImpInterface.java new file mode 100644 index 000000000000..60022bb1d234 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImpInterface.java @@ -0,0 +1,25 @@ +package controllers; + +import java.util.Map; +import apimodels.Order; + +import play.mvc.Http; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; + +import javax.validation.constraints.*; + +@SuppressWarnings("RedundantThrows") +public interface StoreApiControllerImpInterface { + void deleteOrder(String orderId) throws Exception; + + CompletionStage> getInventory() throws Exception; + + CompletionStage getOrderById( @Min(1) @Max(5)Long orderId) throws Exception; + + CompletionStage placeOrder(Order body) throws Exception; + +} diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiController.java new file mode 100644 index 000000000000..fce7743435f7 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiController.java @@ -0,0 +1,172 @@ +package controllers; + +import java.util.List; +import apimodels.User; + +import play.mvc.Controller; +import play.mvc.Result; +import play.mvc.Http; +import java.util.List; +import java.util.Map; +import java.util.ArrayList; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.google.inject.Inject; +import java.io.File; +import swagger.SwaggerUtils; +import com.fasterxml.jackson.core.type.TypeReference; + +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; + +import javax.validation.constraints.*; +import play.Configuration; + +import swagger.SwaggerUtils.ApiAction; + + +public class UserApiController extends Controller { + + private final UserApiControllerImpInterface imp; + private final ObjectMapper mapper; + private final Configuration configuration; + + @Inject + private UserApiController(Configuration configuration, UserApiControllerImpInterface imp) { + this.imp = imp; + mapper = new ObjectMapper(); + this.configuration = configuration; + } + + + @ApiAction + public CompletionStage createUser() throws Exception { + JsonNode nodebody = request().body().asJson(); + User body; + if (nodebody != null) { + body = mapper.readValue(nodebody.toString(), User.class); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } + } else { + throw new IllegalArgumentException("'body' parameter is required"); + } + return CompletableFuture.supplyAsync(() -> { + imp.createUser(body) + return ok(); + }); + } + + @ApiAction + public CompletionStage createUsersWithArrayInput() throws Exception { + JsonNode nodebody = request().body().asJson(); + List body; + if (nodebody != null) { + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } + } + } else { + throw new IllegalArgumentException("'body' parameter is required"); + } + return CompletableFuture.supplyAsync(() -> { + imp.createUsersWithArrayInput(body) + return ok(); + }); + } + + @ApiAction + public CompletionStage createUsersWithListInput() throws Exception { + JsonNode nodebody = request().body().asJson(); + List body; + if (nodebody != null) { + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } + } + } else { + throw new IllegalArgumentException("'body' parameter is required"); + } + return CompletableFuture.supplyAsync(() -> { + imp.createUsersWithListInput(body) + return ok(); + }); + } + + @ApiAction + public CompletionStage deleteUser(String username) throws Exception { + return CompletableFuture.supplyAsync(() -> { + imp.deleteUser(username) + return ok(); + }); + } + + @ApiAction + public CompletionStage getUserByName(String username) throws Exception { + CompletionStage stage = imp.getUserByName(username).thenApply(obj -> { + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } + return obj; + }); + stage.thenApply(obj -> { + JsonNode result = mapper.valueToTree(obj); + return ok(result); + }); + } + + @ApiAction + public CompletionStage loginUser() throws Exception { + String valueusername = request().getQueryString("username"); + String username; + if (valueusername != null) { + username = valueusername; + } else { + throw new IllegalArgumentException("'username' parameter is required"); + } + String valuepassword = request().getQueryString("password"); + String password; + if (valuepassword != null) { + password = valuepassword; + } else { + throw new IllegalArgumentException("'password' parameter is required"); + } + CompletionStage stage = imp.loginUser(username, password).thenApply(obj -> { + return obj; + }); + stage.thenApply(obj -> { + JsonNode result = mapper.valueToTree(obj); + return ok(result); + }); + } + + @ApiAction + public CompletionStage logoutUser() throws Exception { + return CompletableFuture.supplyAsync(() -> { + imp.logoutUser() + return ok(); + }); + } + + @ApiAction + public CompletionStage updateUser(String username) throws Exception { + JsonNode nodebody = request().body().asJson(); + User body; + if (nodebody != null) { + body = mapper.readValue(nodebody.toString(), User.class); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } + } else { + throw new IllegalArgumentException("'body' parameter is required"); + } + return CompletableFuture.supplyAsync(() -> { + imp.updateUser(username, body) + return ok(); + }); + } +} diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImp.java new file mode 100644 index 000000000000..fa6028517c0b --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImp.java @@ -0,0 +1,60 @@ +package controllers; + +import java.util.List; +import apimodels.User; + +import play.mvc.Http; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.io.FileInputStream; +import javax.validation.constraints.*; + +public class UserApiControllerImp implements UserApiControllerImpInterface { + @Override + public void createUser(User body) throws Exception { + //Do your magic!!! + } + + @Override + public void createUsersWithArrayInput(List body) throws Exception { + //Do your magic!!! + } + + @Override + public void createUsersWithListInput(List body) throws Exception { + //Do your magic!!! + } + + @Override + public void deleteUser(String username) throws Exception { + //Do your magic!!! + } + + @Override + public CompletionStage getUserByName(String username) throws Exception { + //Do your magic!!! + return CompletableFuture.supplyAsync(() -> { + return new User(); + }); + } + + @Override + public CompletionStage loginUser( @NotNull String username, @NotNull String password) throws Exception { + //Do your magic!!! + return CompletableFuture.supplyAsync(() -> { + return new String(); + }); + } + + @Override + public void logoutUser() throws Exception { + //Do your magic!!! + } + + @Override + public void updateUser(String username, User body) throws Exception { + //Do your magic!!! + } + +} diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImpInterface.java new file mode 100644 index 000000000000..09b1d5042f02 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImpInterface.java @@ -0,0 +1,33 @@ +package controllers; + +import java.util.List; +import apimodels.User; + +import play.mvc.Http; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; + +import javax.validation.constraints.*; + +@SuppressWarnings("RedundantThrows") +public interface UserApiControllerImpInterface { + void createUser(User body) throws Exception; + + void createUsersWithArrayInput(List body) throws Exception; + + void createUsersWithListInput(List body) throws Exception; + + void deleteUser(String username) throws Exception; + + CompletionStage getUserByName(String username) throws Exception; + + CompletionStage loginUser( @NotNull String username, @NotNull String password) throws Exception; + + void logoutUser() throws Exception; + + void updateUser(String username, User body) throws Exception; + +} diff --git a/samples/server/petstore/java-play-framework-async/app/swagger/ApiCall.java b/samples/server/petstore/java-play-framework-async/app/swagger/ApiCall.java new file mode 100644 index 000000000000..2ca308045b64 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/swagger/ApiCall.java @@ -0,0 +1,27 @@ +package swagger; + +import com.google.inject.Inject; +import play.mvc.Action; +import play.mvc.Http; +import play.mvc.Result; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; + +public class ApiCall extends Action { + + @Inject + private ApiCall() {} + + public CompletionStage call(Http.Context ctx) { + try { + //TODO: Do stuff you want to handle with each API call (metrics, logging, etc..) + return delegate.call(ctx); + } catch (Throwable t) { + //TODO: log the error in your metric + + //We rethrow this error so it will be caught in the ErrorHandler + throw t; + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-async/app/swagger/ErrorHandler.java b/samples/server/petstore/java-play-framework-async/app/swagger/ErrorHandler.java new file mode 100644 index 000000000000..2c813411a5e5 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/swagger/ErrorHandler.java @@ -0,0 +1,49 @@ +package swagger; + + +import play.*; +import play.api.OptionalSourceMapper; +import play.api.UsefulException; +import play.api.routing.Router; +import play.http.DefaultHttpErrorHandler; +import play.mvc.Http.*; +import play.mvc.*; + +import javax.inject.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import static play.mvc.Results.*; + +@Singleton +public class ErrorHandler extends DefaultHttpErrorHandler { + + @Inject + public ErrorHandler(Configuration configuration, Environment environment, OptionalSourceMapper sourceMapper, Provider routes) { + super(configuration, environment, sourceMapper, routes); + } + + @Override + protected CompletionStage onDevServerError(RequestHeader request, UsefulException exception) { + return CompletableFuture.completedFuture( + handleExceptions(exception) + ); + } + + @Override + protected CompletionStage onProdServerError(RequestHeader request, UsefulException exception) { + return CompletableFuture.completedFuture( + handleExceptions(exception) + ); + } + + @Override + protected void logServerError(RequestHeader request, UsefulException usefulException) { + //Since the error is already handled, we don't want to print anything on the console + //But if you want to have the error printed in the console, just delete this override + } + + private Result handleExceptions(Throwable t) { + //TODO: Handle exception that need special response (return a special apimodel, notFound(), etc..) + return ok(); + } +} diff --git a/samples/server/petstore/java-play-framework-async/app/swagger/SwaggerUtils.java b/samples/server/petstore/java-play-framework-async/app/swagger/SwaggerUtils.java new file mode 100644 index 000000000000..d4900e021677 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/app/swagger/SwaggerUtils.java @@ -0,0 +1,103 @@ +package swagger; + +import play.mvc.With; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.text.SimpleDateFormat; +import java.util.*; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +public class SwaggerUtils { + + @With(ApiCall.class) + @Target({ ElementType.TYPE, ElementType.METHOD }) + @Retention(RetentionPolicy.RUNTIME) + public @interface ApiAction { + } + + public static void validate(T obj) { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> constraintViolations = validator.validate(obj); + if (constraintViolations.size() > 0) { + StringBuilder errors = new StringBuilder(); + for (ConstraintViolation contraintes : constraintViolations) { + errors.append(String.format("%s.%s %s\n", + contraintes.getRootBeanClass().getSimpleName(), + contraintes.getPropertyPath(), + contraintes.getMessage())); + } + throw new RuntimeException("Bean validation : " + errors); + } + } + + public static List parametersToList(String collectionFormat, String[] values){ + List params = new ArrayList<>(); + + if (values == null) { + return params; + } + + if (values.length >= 1 && collectionFormat.equals("multi")) { + params.addAll(Arrays.asList(values)); + } else { + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + String delimiter = ","; + + switch(collectionFormat) { + case "csv": { + delimiter = ","; + break; + } + case "ssv": { + delimiter = " "; + break; + } + case "tsv": { + delimiter = "\t"; + break; + } + case "pipes": { + delimiter = "|"; + break; + } + } + + params = Arrays.asList(values[0].split(delimiter)); + } + + return params; + } + + public static String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + + return b.toString(); + } else { + return String.valueOf(param); + } + } + + public static String formatDatetime(Date date) { + return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(date); + } +} \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-async/build.sbt b/samples/server/petstore/java-play-framework-async/build.sbt new file mode 100644 index 000000000000..e425cf8cfe64 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/build.sbt @@ -0,0 +1,11 @@ +name := """swagger-java-playframework""" + +version := "1.0-SNAPSHOT" + +lazy val root = (project in file(".")).enablePlugins(PlayJava) + +scalaVersion := "2.12.2" + +libraryDependencies += "org.webjars" % "swagger-ui" % "3.1.5" +libraryDependencies += "javax.validation" % "validation-api" % "1.1.0.Final" +libraryDependencies += guice diff --git a/samples/server/petstore/java-play-framework-async/conf/application.conf b/samples/server/petstore/java-play-framework-async/conf/application.conf new file mode 100644 index 000000000000..bcd07672dc10 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/conf/application.conf @@ -0,0 +1,374 @@ +# This is the main configuration file for the application. +# https://www.playframework.com/documentation/latest/ConfigFile +# ~~~~~ +# Play uses HOCON as its configuration file format. HOCON has a number +# of advantages over other config formats, but there are two things that +# can be used when modifying settings. +# +# You can include other configuration files in this main application.conf file: +#include "extra-config.conf" +# +# You can declare variables and substitute for them: +#mykey = ${some.value} +# +# And if an environment variable exists when there is no other subsitution, then +# HOCON will fall back to substituting environment variable: +#mykey = ${JAVA_HOME} + +play.filters.headers.contentSecurityPolicy=null + +# When using bean validation with the swagger api, the validator will check that every constraint is respected +# This is very useful when testing but could add a lot of overhead if you return a lot of data. Benchmark have +# shown that the time it takes to validate is exponential. +# If this is a concern in your application, or if you don't want to validate the output coming from your API for +# respecting its contract, set the "output" property below to "false". Since there is not a lot of data as input for +# an endpoint, I highly suggest you let the "input" property set to true. +useInputBeanValidation=true +useOutputBeanValidation=true + +play.http.errorHandler="swagger.ErrorHandler" + +## Akka +# https://www.playframework.com/documentation/latest/ScalaAkka#Configuration +# https://www.playframework.com/documentation/latest/JavaAkka#Configuration +# ~~~~~ +# Play uses Akka internally and exposes Akka Streams and actors in Websockets and +# other streaming HTTP responses. +akka { +# "akka.log-config-on-start" is extraordinarily useful because it log the complete +# configuration at INFO level, including defaults and overrides, so it s worth +# putting at the very top. +# +# Put the following in your conf/logback.xml file: +# +# +# +# And then uncomment this line to debug the configuration. +# +#log-config-on-start = true +} + +## Secret key +# http://www.playframework.com/documentation/latest/ApplicationSecret +# ~~~~~ +# The secret key is used to sign Play's session cookie. +# This must be changed for production, but we don't recommend you change it in this file. +play.http.secret.key = "changeme" + +## Modules +# https://www.playframework.com/documentation/latest/Modules +# ~~~~~ +# Control which modules are loaded when Play starts. Note that modules are +# the replacement for "GlobalSettings", which are deprecated in 2.5.x. +# Please see https://www.playframework.com/documentation/latest/GlobalSettings +# for more information. +# +# You can also extend Play functionality by using one of the publically available +# Play modules: https://playframework.com/documentation/latest/ModuleDirectory +play.modules { +# By default, Play will load any class called Module that is defined +# in the root package (the "app" directory), or you can define them +# explicitly below. +# If there are any built-in modules that you want to disable, you can list them here. +} + +play.assets { +path = "/public" +urlPrefix = "/assets" +} + +## IDE +# https://www.playframework.com/documentation/latest/IDE +# ~~~~~ +# Depending on your IDE, you can add a hyperlink for errors that will jump you +# directly to the code location in the IDE in dev mode. The following line makes +# use of the IntelliJ IDEA REST interface: +#play.editor="http://localhost:63342/api/file/?file=%s&line=%s" + +## Internationalisation +# https://www.playframework.com/documentation/latest/JavaI18N +# https://www.playframework.com/documentation/latest/ScalaI18N +# ~~~~~ +# Play comes with its own i18n settings, which allow the user's preferred language +# to map through to internal messages, or allow the language to be stored in a cookie. +play.i18n { +# The application languages +langs = [ "en" ] + +# Whether the language cookie should be secure or not +#langCookieSecure = true + +# Whether the HTTP only attribute of the cookie should be set to true +#langCookieHttpOnly = true +} + +## Play HTTP settings +# ~~~~~ +play.http { +## Router +# https://www.playframework.com/documentation/latest/JavaRouting +# https://www.playframework.com/documentation/latest/ScalaRouting +# ~~~~~ +# Define the Router object to use for this application. +# This router will be looked up first when the application is starting up, +# so make sure this is the entry point. +# Furthermore, it's assumed your route file is named properly. +# So for an application router like `my.application.Router`, +# you may need to define a router file `conf/my.application.routes`. +# Default to Routes in the root package (aka "apps" folder) (and conf/routes) +#router = my.application.Router + +## Action Creator +# https://www.playframework.com/documentation/latest/JavaActionCreator +# ~~~~~ +#actionCreator = null + +## ErrorHandler +# https://www.playframework.com/documentation/latest/JavaRouting +# https://www.playframework.com/documentation/latest/ScalaRouting +# ~~~~~ +# If null, will attempt to load a class called ErrorHandler in the root package, +#errorHandler = null + +## Filters +# https://www.playframework.com/documentation/latest/ScalaHttpFilters +# https://www.playframework.com/documentation/latest/JavaHttpFilters +# ~~~~~ +# Filters run code on every request. They can be used to perform +# common logic for all your actions, e.g. adding common headers. +# Defaults to "Filters" in the root package (aka "apps" folder) +# Alternatively you can explicitly register a class here. +#filters = my.application.Filters + +## Session & Flash +# https://www.playframework.com/documentation/latest/JavaSessionFlash +# https://www.playframework.com/documentation/latest/ScalaSessionFlash +# ~~~~~ +session { +# Sets the cookie to be sent only over HTTPS. +#secure = true + +# Sets the cookie to be accessed only by the server. +#httpOnly = true + +# Sets the max-age field of the cookie to 5 minutes. +# NOTE: this only sets when the browser will discard the cookie. Play will consider any +# cookie value with a valid signature to be a valid session forever. To implement a server side session timeout, +# you need to put a timestamp in the session and check it at regular intervals to possibly expire it. +#maxAge = 300 + +# Sets the domain on the session cookie. +#domain = "example.com" +} + +flash { +# Sets the cookie to be sent only over HTTPS. +#secure = true + +# Sets the cookie to be accessed only by the server. +#httpOnly = true +} +} + +## Netty Provider +# https://www.playframework.com/documentation/latest/SettingsNetty +# ~~~~~ +play.server.netty { +# Whether the Netty wire should be logged +#log.wire = true + +# If you run Play on Linux, you can use Netty's native socket transport +# for higher performance with less garbage. +#transport = "native" +} + +## WS (HTTP Client) +# https://www.playframework.com/documentation/latest/ScalaWS#Configuring-WS +# ~~~~~ +# The HTTP client primarily used for REST APIs. The default client can be +# configured directly, but you can also create different client instances +# with customized settings. You must enable this by adding to build.sbt: +# +# libraryDependencies += ws // or javaWs if using java +# +play.ws { +# Sets HTTP requests not to follow 302 requests +#followRedirects = false + +# Sets the maximum number of open HTTP connections for the client. +#ahc.maxConnectionsTotal = 50 + +## WS SSL +# https://www.playframework.com/documentation/latest/WsSSL +# ~~~~~ +ssl { +# Configuring HTTPS with Play WS does not require programming. You can +# set up both trustManager and keyManager for mutual authentication, and +# turn on JSSE debugging in development with a reload. +#debug.handshake = true +#trustManager = { +# stores = [ +# { type = "JKS", path = "exampletrust.jks" } +# ] +#} +} +} + +## Cache +# https://www.playframework.com/documentation/latest/JavaCache +# https://www.playframework.com/documentation/latest/ScalaCache +# ~~~~~ +# Play comes with an integrated cache API that can reduce the operational +# overhead of repeated requests. You must enable this by adding to build.sbt: +# +# libraryDependencies += cache +# +play.cache { +# If you want to bind several caches, you can bind the individually +#bindCaches = ["db-cache", "user-cache", "session-cache"] +} + +## Filters +# https://www.playframework.com/documentation/latest/Filters +# ~~~~~ +# There are a number of built-in filters that can be enabled and configured +# to give Play greater security. You must enable this by adding to build.sbt: +# +# libraryDependencies += filters +# +play.filters { +## CORS filter configuration +# https://www.playframework.com/documentation/latest/CorsFilter +# ~~~~~ +# CORS is a protocol that allows web applications to make requests from the browser +# across different domains. +# NOTE: You MUST apply the CORS configuration before the CSRF filter, as CSRF has +# dependencies on CORS settings. +cors { +# Filter paths by a whitelist of path prefixes +#pathPrefixes = ["/some/path", ...] + +# The allowed origins. If null, all origins are allowed. +#allowedOrigins = ["http://www.example.com"] + +# The allowed HTTP methods. If null, all methods are allowed +#allowedHttpMethods = ["GET", "POST"] +} + +## CSRF Filter +# https://www.playframework.com/documentation/latest/ScalaCsrf#Applying-a-global-CSRF-filter +# https://www.playframework.com/documentation/latest/JavaCsrf#Applying-a-global-CSRF-filter +# ~~~~~ +# Play supports multiple methods for verifying that a request is not a CSRF request. +# The primary mechanism is a CSRF token. This token gets placed either in the query string +# or body of every form submitted, and also gets placed in the users session. +# Play then verifies that both tokens are present and match. +csrf { +# Sets the cookie to be sent only over HTTPS +#cookie.secure = true + +# Defaults to CSRFErrorHandler in the root package. +#errorHandler = MyCSRFErrorHandler +} + +## Security headers filter configuration +# https://www.playframework.com/documentation/latest/SecurityHeaders +# ~~~~~ +# Defines security headers that prevent XSS attacks. +# If enabled, then all options are set to the below configuration by default: +play.filters.headers { + +# The X-Frame-Options header. If null, the header is not set. +#frameOptions = "DENY" + +# The X-XSS-Protection header. If null, the header is not set. +#xssProtection = "1; mode=block" + +# The X-Content-Type-Options header. If null, the header is not set. +#contentTypeOptions = "nosniff" + +# The X-Permitted-Cross-Domain-Policies header. If null, the header is not set. +#permittedCrossDomainPolicies = "master-only" + +# The Content-Security-Policy header. If null, the header is not set. +contentSecurityPolicy = "default-src 'self'" + +# The Referrer-Policy header. If null, the header is not set. +#referrerPolicy = "origin-when-cross-origin, strict-origin-when-cross-origin" + +# If true, allow an action to use .withHeaders to replace one or more of the above headers +#allowActionSpecificHeaders = false +} + +## Allowed hosts filter configuration +# https://www.playframework.com/documentation/latest/AllowedHostsFilter +# ~~~~~ +# Play provides a filter that lets you configure which hosts can access your application. +# This is useful to prevent cache poisoning attacks. +hosts { +# Allow requests to example.com, its subdomains, and localhost:9000. +#allowed = [".example.com", "localhost:9000"] +} +} + +## Evolutions +# https://www.playframework.com/documentation/latest/Evolutions +# ~~~~~ +# Evolutions allows database scripts to be automatically run on startup in dev mode +# for database migrations. You must enable this by adding to build.sbt: +# +# libraryDependencies += evolutions +# +play.evolutions { +# You can disable evolutions for a specific datasource if necessary +#db.default.enabled = false +} + +## Database Connection Pool +# https://www.playframework.com/documentation/latest/SettingsJDBC +# ~~~~~ +# Play doesn't require a JDBC database to run, but you can easily enable one. +# +# libraryDependencies += jdbc +# +play.db { +# The combination of these two settings results in "db.default" as the +# default JDBC pool: +#config = "db" +#default = "default" + +# Play uses HikariCP as the default connection pool. You can override +# settings by changing the prototype: +prototype { +# Sets a fixed JDBC connection pool size of 50 +#hikaricp.minimumIdle = 50 +#hikaricp.maximumPoolSize = 50 +} +} + +## JDBC Datasource +# https://www.playframework.com/documentation/latest/JavaDatabase +# https://www.playframework.com/documentation/latest/ScalaDatabase +# ~~~~~ +# Once JDBC datasource is set up, you can work with several different +# database options: +# +# Slick (Scala preferred option): https://www.playframework.com/documentation/latest/PlaySlick +# JPA (Java preferred option): https://playframework.com/documentation/latest/JavaJPA +# EBean: https://playframework.com/documentation/latest/JavaEbean +# Anorm: https://www.playframework.com/documentation/latest/ScalaAnorm +# +db { +# You can declare as many datasources as you want. +# By convention, the default datasource is named `default` + +# https://www.playframework.com/documentation/latest/Developing-with-the-H2-Database +#default.driver = org.h2.Driver +#default.url = "jdbc:h2:mem:play" +#default.username = sa +#default.password = "" + +# You can turn on SQL logging for any datasource +# https://www.playframework.com/documentation/latest/Highlights25#Logging-SQL-statements +#default.logSql=true +} diff --git a/samples/server/petstore/java-play-framework-async/conf/logback.xml b/samples/server/petstore/java-play-framework-async/conf/logback.xml new file mode 100644 index 000000000000..01f301ab73a9 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/conf/logback.xml @@ -0,0 +1,41 @@ + + + + + + + ${application.home:-.}/logs/application.log + + %date [%level] from %logger in %thread - %message%n%xException + + + + + + %coloredLevel %logger{15} - %message%n%xException{10} + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/server/petstore/java-play-framework-async/conf/routes b/samples/server/petstore/java-play-framework-async/conf/routes new file mode 100644 index 000000000000..775497a59fcb --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/conf/routes @@ -0,0 +1,36 @@ +# Routes +# This file defines all application routes (Higher priority routes first) +# ~~~~ + +GET /api controllers.ApiDocController.api + + +#Functions for Pet API +POST /v2/pet controllers.PetApiController.addPet() +DELETE /v2/pet/:petId controllers.PetApiController.deletePet(petId: Long) +GET /v2/pet/findByStatus controllers.PetApiController.findPetsByStatus() +GET /v2/pet/findByTags controllers.PetApiController.findPetsByTags() +GET /v2/pet/:petId controllers.PetApiController.getPetById(petId: Long) +PUT /v2/pet controllers.PetApiController.updatePet() +POST /v2/pet/:petId controllers.PetApiController.updatePetWithForm(petId: Long) +POST /v2/pet/:petId/uploadImage controllers.PetApiController.uploadFile(petId: Long) + +#Functions for Store API +DELETE /v2/store/order/:orderId controllers.StoreApiController.deleteOrder(orderId: String) +GET /v2/store/inventory controllers.StoreApiController.getInventory() +GET /v2/store/order/:orderId controllers.StoreApiController.getOrderById(orderId: Long) +POST /v2/store/order controllers.StoreApiController.placeOrder() + +#Functions for User API +POST /v2/user controllers.UserApiController.createUser() +POST /v2/user/createWithArray controllers.UserApiController.createUsersWithArrayInput() +POST /v2/user/createWithList controllers.UserApiController.createUsersWithListInput() +DELETE /v2/user/:username controllers.UserApiController.deleteUser(username: String) +GET /v2/user/:username controllers.UserApiController.getUserByName(username: String) +GET /v2/user/login controllers.UserApiController.loginUser() +GET /v2/user/logout controllers.UserApiController.logoutUser() +PUT /v2/user/:username controllers.UserApiController.updateUser(username: String) + +# Map static resources from the /public folder to the /assets URL path +GET /assets/*file controllers.Assets.at(file) +GET /versionedAssets/*file controllers.Assets.versioned(file) \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-async/project/build.properties b/samples/server/petstore/java-play-framework-async/project/build.properties new file mode 100644 index 000000000000..cf19fd026fd1 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.13.15 \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-async/project/plugins.sbt b/samples/server/petstore/java-play-framework-async/project/plugins.sbt new file mode 100644 index 000000000000..66fbf368ae61 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/project/plugins.sbt @@ -0,0 +1,2 @@ +// The Play plugin +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.3") diff --git a/samples/server/petstore/java-play-framework-async/public/swagger.json b/samples/server/petstore/java-play-framework-async/public/swagger.json new file mode 100644 index 000000000000..3ab9cda2ce83 --- /dev/null +++ b/samples/server/petstore/java-play-framework-async/public/swagger.json @@ -0,0 +1,907 @@ +{ + "swagger" : "2.0", + "info" : { + "description" : "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "version" : "1.0.0", + "title" : "Swagger Petstore", + "termsOfService" : "http://swagger.io/terms/", + "contact" : { + "email" : "apiteam@swagger.io" + }, + "license" : { + "name" : "Apache-2.0", + "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "basePath" : "/v2", + "tags" : [ { + "name" : "pet", + "description" : "Everything about your Pets", + "externalDocs" : { + "description" : "Find out more", + "url" : "http://swagger.io" + } + }, { + "name" : "store", + "description" : "Access to Petstore orders" + }, { + "name" : "user", + "description" : "Operations about user", + "externalDocs" : { + "description" : "Find out more about our store", + "url" : "http://swagger.io" + } + } ], + "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" ] + } ], + "x-contentType" : "application/json", + "x-accepts" : "application/json" + }, + "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" ] + } ], + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/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" ] + } ], + "x-accepts" : "application/json" + } + }, + "/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, + "x-accepts" : "application/json" + } + }, + "/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" : [ ] + } ], + "x-accepts" : "application/json" + }, + "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" + }, { + "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" + } ], + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "x-contentType" : "application/x-www-form-urlencoded", + "x-accepts" : "application/json" + }, + "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" ] + } ], + "x-accepts" : "application/json" + } + }, + "/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" ] + } ], + "x-contentType" : "multipart/form-data", + "x-accepts" : "application/json" + } + }, + "/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" : [ ] + } ], + "x-accepts" : "application/json" + } + }, + "/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" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/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" + } + }, + "x-accepts" : "application/json" + }, + "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" + } + }, + "x-accepts" : "application/json" + } + }, + "/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" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/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" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/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" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/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" + } + }, + "x-accepts" : "application/json" + } + }, + "/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" + } + }, + "x-accepts" : "application/json" + } + }, + "/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" + } + }, + "x-accepts" : "application/json" + }, + "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" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + }, + "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" + } + }, + "x-accepts" : "application/json" + } + } + }, + "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" : { + "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 + } + }, + "title" : "Pet Order", + "description" : "An order for a pets from the pet store", + "example" : { + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" + }, + "xml" : { + "name" : "Order" + } + }, + "Category" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet category", + "description" : "A category for a pet", + "example" : { + "name" : "name", + "id" : 6 + }, + "xml" : { + "name" : "Category" + } + }, + "User" : { + "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" + } + }, + "title" : "a User", + "description" : "A User who is purchasing from the pet store", + "example" : { + "firstName" : "firstName", + "lastName" : "lastName", + "password" : "password", + "userStatus" : 6, + "phone" : "phone", + "id" : 0, + "email" : "email", + "username" : "username" + }, + "xml" : { + "name" : "User" + } + }, + "Tag" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet Tag", + "description" : "A tag for a pet", + "example" : { + "name" : "name", + "id" : 1 + }, + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "type" : "object", + "required" : [ "name", "photoUrls" ], + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "category" : { + "$ref" : "#/definitions/Category" + }, + "name" : { + "type" : "string", + "example" : "doggie" + }, + "photoUrls" : { + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + }, + "items" : { + "type" : "string" + } + }, + "tags" : { + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + }, + "items" : { + "$ref" : "#/definitions/Tag" + } + }, + "status" : { + "type" : "string", + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ] + } + }, + "title" : "a Pet", + "description" : "A pet for sale in the pet store", + "example" : { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" + }, + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "type" : "object", + "properties" : { + "code" : { + "type" : "integer", + "format" : "int32" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + }, + "title" : "An uploaded response", + "description" : "Describes the result of uploading an image resource", + "example" : { + "code" : 0, + "type" : "type", + "message" : "message" + } + } + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" + } +} \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-controller-only/public/swagger.json b/samples/server/petstore/java-play-framework-controller-only/public/swagger.json index 0f5defa60266..3ab9cda2ce83 100644 --- a/samples/server/petstore/java-play-framework-controller-only/public/swagger.json +++ b/samples/server/petstore/java-play-framework-controller-only/public/swagger.json @@ -13,7 +13,6 @@ "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" } }, - "host" : "petstore.swagger.io", "basePath" : "/v2", "tags" : [ { "name" : "pet", @@ -112,8 +111,8 @@ "type" : "array", "items" : { "type" : "string", - "default" : "available", - "enum" : [ "available", "pending", "sold" ] + "enum" : [ "available", "pending", "sold" ], + "default" : "available" }, "collectionFormat" : "csv" } ], @@ -588,7 +587,7 @@ "parameters" : [ { "name" : "username", "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing. ", + "description" : "The name that needs to be fetched. Use user1 for testing.", "required" : true, "type" : "string" } ], diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/public/swagger.json b/samples/server/petstore/java-play-framework-fake-endpoints/public/swagger.json index d23a6018638f..dca4e4b58a98 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/public/swagger.json +++ b/samples/server/petstore/java-play-framework-fake-endpoints/public/swagger.json @@ -112,8 +112,8 @@ "type" : "array", "items" : { "type" : "string", - "default" : "available", - "enum" : [ "available", "pending", "sold" ] + "enum" : [ "available", "pending", "sold" ], + "default" : "available" }, "collectionFormat" : "csv" } ], @@ -588,7 +588,7 @@ "parameters" : [ { "name" : "username", "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing. ", + "description" : "The name that needs to be fetched. Use user1 for testing.", "required" : true, "type" : "string" } ], @@ -711,8 +711,8 @@ "type" : "array", "items" : { "type" : "string", - "default" : "$", - "enum" : [ ">", "$" ] + "enum" : [ ">", "$" ], + "default" : "$" } }, { "name" : "enum_form_string", @@ -730,8 +730,8 @@ "type" : "array", "items" : { "type" : "string", - "default" : "$", - "enum" : [ ">", "$" ] + "enum" : [ ">", "$" ], + "default" : "$" } }, { "name" : "enum_header_string", @@ -749,8 +749,8 @@ "type" : "array", "items" : { "type" : "string", - "default" : "$", - "enum" : [ ">", "$" ] + "enum" : [ ">", "$" ], + "default" : "$" } }, { "name" : "enum_query_string", diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/public/swagger.json b/samples/server/petstore/java-play-framework-no-bean-validation/public/swagger.json index 0f5defa60266..3ab9cda2ce83 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/public/swagger.json +++ b/samples/server/petstore/java-play-framework-no-bean-validation/public/swagger.json @@ -13,7 +13,6 @@ "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" } }, - "host" : "petstore.swagger.io", "basePath" : "/v2", "tags" : [ { "name" : "pet", @@ -112,8 +111,8 @@ "type" : "array", "items" : { "type" : "string", - "default" : "available", - "enum" : [ "available", "pending", "sold" ] + "enum" : [ "available", "pending", "sold" ], + "default" : "available" }, "collectionFormat" : "csv" } ], @@ -588,7 +587,7 @@ "parameters" : [ { "name" : "username", "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing. ", + "description" : "The name that needs to be fetched. Use user1 for testing.", "required" : true, "type" : "string" } ], diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/public/swagger.json b/samples/server/petstore/java-play-framework-no-exception-handling/public/swagger.json index 0f5defa60266..3ab9cda2ce83 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/public/swagger.json +++ b/samples/server/petstore/java-play-framework-no-exception-handling/public/swagger.json @@ -13,7 +13,6 @@ "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" } }, - "host" : "petstore.swagger.io", "basePath" : "/v2", "tags" : [ { "name" : "pet", @@ -112,8 +111,8 @@ "type" : "array", "items" : { "type" : "string", - "default" : "available", - "enum" : [ "available", "pending", "sold" ] + "enum" : [ "available", "pending", "sold" ], + "default" : "available" }, "collectionFormat" : "csv" } ], @@ -588,7 +587,7 @@ "parameters" : [ { "name" : "username", "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing. ", + "description" : "The name that needs to be fetched. Use user1 for testing.", "required" : true, "type" : "string" } ], diff --git a/samples/server/petstore/java-play-framework-no-interface/public/swagger.json b/samples/server/petstore/java-play-framework-no-interface/public/swagger.json index 0f5defa60266..3ab9cda2ce83 100644 --- a/samples/server/petstore/java-play-framework-no-interface/public/swagger.json +++ b/samples/server/petstore/java-play-framework-no-interface/public/swagger.json @@ -13,7 +13,6 @@ "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" } }, - "host" : "petstore.swagger.io", "basePath" : "/v2", "tags" : [ { "name" : "pet", @@ -112,8 +111,8 @@ "type" : "array", "items" : { "type" : "string", - "default" : "available", - "enum" : [ "available", "pending", "sold" ] + "enum" : [ "available", "pending", "sold" ], + "default" : "available" }, "collectionFormat" : "csv" } ], @@ -588,7 +587,7 @@ "parameters" : [ { "name" : "username", "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing. ", + "description" : "The name that needs to be fetched. Use user1 for testing.", "required" : true, "type" : "string" } ], diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/public/swagger.json b/samples/server/petstore/java-play-framework-no-wrap-calls/public/swagger.json index 0f5defa60266..3ab9cda2ce83 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/public/swagger.json +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/public/swagger.json @@ -13,7 +13,6 @@ "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" } }, - "host" : "petstore.swagger.io", "basePath" : "/v2", "tags" : [ { "name" : "pet", @@ -112,8 +111,8 @@ "type" : "array", "items" : { "type" : "string", - "default" : "available", - "enum" : [ "available", "pending", "sold" ] + "enum" : [ "available", "pending", "sold" ], + "default" : "available" }, "collectionFormat" : "csv" } ], @@ -588,7 +587,7 @@ "parameters" : [ { "name" : "username", "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing. ", + "description" : "The name that needs to be fetched. Use user1 for testing.", "required" : true, "type" : "string" } ], diff --git a/samples/server/petstore/java-play-framework/public/swagger.json b/samples/server/petstore/java-play-framework/public/swagger.json index 0f5defa60266..3ab9cda2ce83 100644 --- a/samples/server/petstore/java-play-framework/public/swagger.json +++ b/samples/server/petstore/java-play-framework/public/swagger.json @@ -13,7 +13,6 @@ "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" } }, - "host" : "petstore.swagger.io", "basePath" : "/v2", "tags" : [ { "name" : "pet", @@ -112,8 +111,8 @@ "type" : "array", "items" : { "type" : "string", - "default" : "available", - "enum" : [ "available", "pending", "sold" ] + "enum" : [ "available", "pending", "sold" ], + "default" : "available" }, "collectionFormat" : "csv" } ], @@ -588,7 +587,7 @@ "parameters" : [ { "name" : "username", "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing. ", + "description" : "The name that needs to be fetched. Use user1 for testing.", "required" : true, "type" : "string" } ], diff --git a/samples/server/petstore/jaxrs-cxf/.swagger-codegen/VERSION b/samples/server/petstore/jaxrs-cxf/.swagger-codegen/VERSION index f9f7450d1359..855ff9501eb8 100644 --- a/samples/server/petstore/jaxrs-cxf/.swagger-codegen/VERSION +++ b/samples/server/petstore/jaxrs-cxf/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.0-SNAPSHOT \ No newline at end of file +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeClassnameTags123Api.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeClassnameTags123Api.java index 63de6839dc1d..d7180a4ae80d 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeClassnameTags123Api.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeClassnameTags123Api.java @@ -30,6 +30,8 @@ public interface FakeClassnameTags123Api { /** + * To test class name in snake case + * * To test class name in snake case * */ diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java index 065420cf3572..170ef45f20ed 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java @@ -73,7 +73,7 @@ public interface StoreApi { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Order not found") }) - public Order getOrderById(@PathParam("order_id") @Min(1) @Max(5) Long orderId); + public Order getOrderById(@PathParam("order_id") @Min(1L) @Max(5L) Long orderId); /** * Place an order for a pet diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java index 353bc6e2cbc5..17e16e8f72d4 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Map; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -21,6 +22,7 @@ public class AdditionalPropertiesClass { private Map mapProperty = null; @ApiModelProperty(value = "") + @Valid private Map> mapOfMapProperty = null; /** * Get mapProperty diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Animal.java index 2962c676df84..ec63c65ca3fd 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Animal.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AnimalFarm.java index f124292c31d4..433dec45a3ec 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AnimalFarm.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.List; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index de5d9f8863cb..e384af40a688 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.List; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -18,6 +19,7 @@ public class ArrayOfArrayOfNumberOnly { @ApiModelProperty(value = "") + @Valid private List> arrayArrayNumber = null; /** * Get arrayArrayNumber diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java index d9e2795aa972..c46dc7b48df7 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.List; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -18,6 +19,7 @@ public class ArrayOfNumberOnly { @ApiModelProperty(value = "") + @Valid private List arrayNumber = null; /** * Get arrayNumber diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayTest.java index fa3e7f481abe..aa599a49e8b2 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayTest.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.List; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -21,9 +22,11 @@ public class ArrayTest { private List arrayOfString = null; @ApiModelProperty(value = "") + @Valid private List> arrayArrayOfInteger = null; @ApiModelProperty(value = "") + @Valid private List> arrayArrayOfModel = null; /** * Get arrayOfString diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Capitalization.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Capitalization.java index 7333898c61f2..a13ea6d9039b 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Capitalization.java @@ -1,6 +1,7 @@ package io.swagger.model; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -31,7 +32,7 @@ public class Capitalization { @ApiModelProperty(value = "Name of the pet ") /** - * Name of the pet + * Name of the pet **/ private String ATT_NAME = null; /** diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Cat.java index f5af4d9c7337..45151da21a14 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Cat.java @@ -2,6 +2,7 @@ import io.swagger.model.Animal; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java index 2be982a410b5..c555cbbf10dc 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java @@ -1,6 +1,7 @@ package io.swagger.model; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ClassModel.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ClassModel.java index e3af436a21c9..f8ea47f9ad9b 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ClassModel.java @@ -2,6 +2,7 @@ import io.swagger.annotations.ApiModel; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Client.java index 4d6bd4d03634..93fb0e20b66b 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Client.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Client.java @@ -1,6 +1,7 @@ package io.swagger.model; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Dog.java index aca8d694c72b..6bed49c31542 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Dog.java @@ -2,6 +2,7 @@ import io.swagger.model.Animal; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumArrays.java index ecf3512c1d28..e9828b7fb3de 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumArrays.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.List; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumClass.java index 928ecf719c8f..8434226138ee 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumClass.java @@ -1,6 +1,7 @@ package io.swagger.model; import javax.validation.constraints.*; +import javax.validation.Valid; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumTest.java index 93e832b37b95..e564259dfd10 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumTest.java @@ -2,6 +2,7 @@ import io.swagger.model.OuterEnum; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -52,6 +53,42 @@ public static EnumStringEnum fromValue(String v) { private EnumStringEnum enumString = null; +@XmlType(name="EnumStringRequiredEnum") +@XmlEnum(String.class) +public enum EnumStringRequiredEnum { + +@XmlEnumValue("UPPER") UPPER(String.valueOf("UPPER")), @XmlEnumValue("lower") LOWER(String.valueOf("lower")), @XmlEnumValue("") EMPTY(String.valueOf("")); + + + private String value; + + EnumStringRequiredEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStringRequiredEnum fromValue(String v) { + for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(required = true, value = "") + private EnumStringRequiredEnum enumStringRequired = null; + + @XmlType(name="EnumIntegerEnum") @XmlEnum(Integer.class) public enum EnumIntegerEnum { @@ -124,6 +161,7 @@ public static EnumNumberEnum fromValue(String v) { private EnumNumberEnum enumNumber = null; @ApiModelProperty(value = "") + @Valid private OuterEnum outerEnum = null; /** * Get enumString @@ -146,6 +184,28 @@ public EnumTest enumString(EnumStringEnum enumString) { return this; } + /** + * Get enumStringRequired + * @return enumStringRequired + **/ + @JsonProperty("enum_string_required") + @NotNull + public String getEnumStringRequired() { + if (enumStringRequired == null) { + return null; + } + return enumStringRequired.value(); + } + + public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + } + + public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + return this; + } + /** * Get enumInteger * @return enumInteger @@ -213,6 +273,7 @@ public String toString() { 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"); diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/FormatTest.java index c9085fc2e6f1..3d838ab5ec92 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/FormatTest.java @@ -5,6 +5,7 @@ import java.util.UUID; import org.joda.time.LocalDate; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -28,6 +29,7 @@ public class FormatTest { private Long int64 = null; @ApiModelProperty(required = true, value = "") + @Valid private BigDecimal number = null; @ApiModelProperty(value = "") diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/HasOnlyReadOnly.java index e9ab9aadf50c..675cc8f4eb3b 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -1,6 +1,7 @@ package io.swagger.model; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MapTest.java index fa39d05a2881..557c040e97f0 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MapTest.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Map; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -18,6 +19,7 @@ public class MapTest { @ApiModelProperty(value = "") + @Valid private Map> mapMapOfString = null; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index c86319b2fcad..d54bee75e202 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -7,6 +7,7 @@ import java.util.Map; import java.util.UUID; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -27,6 +28,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { private Date dateTime = null; @ApiModelProperty(value = "") + @Valid private Map map = null; /** * Get uuid diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Model200Response.java index 30e12af1b470..47364cc3b01d 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Model200Response.java @@ -2,6 +2,7 @@ import io.swagger.annotations.ApiModel; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java index 64f77fc254ec..8dda26ada3d3 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -1,6 +1,7 @@ package io.swagger.model; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelReturn.java index 3d11f555a120..eafbe41f5311 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelReturn.java @@ -2,6 +2,7 @@ import io.swagger.annotations.ApiModel; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Name.java index 2c7e77096ed6..94bb6caa53e4 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Name.java @@ -2,6 +2,7 @@ import io.swagger.annotations.ApiModel; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/NumberOnly.java index 8d6e7d662ae3..1318a296e322 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/NumberOnly.java @@ -2,6 +2,7 @@ import java.math.BigDecimal; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -16,6 +17,7 @@ public class NumberOnly { @ApiModelProperty(value = "") + @Valid private BigDecimal justNumber = null; /** * Get justNumber diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java index 4e4a7a75b65f..2d3cab3e0a6e 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java @@ -2,6 +2,7 @@ import java.util.Date; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -62,7 +63,7 @@ public static StatusEnum fromValue(String v) { @ApiModelProperty(value = "Order Status") /** - * Order Status + * Order Status **/ private StatusEnum status = null; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterComposite.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterComposite.java index 33fd0d7c28a0..2d0c2bce5d5a 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterComposite.java @@ -2,6 +2,7 @@ import java.math.BigDecimal; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -16,6 +17,7 @@ public class OuterComposite { @ApiModelProperty(value = "") + @Valid private BigDecimal myNumber = null; @ApiModelProperty(value = "") diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterEnum.java index a95e0f4f052d..09afd692d803 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterEnum.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterEnum.java @@ -1,6 +1,7 @@ package io.swagger.model; import javax.validation.constraints.*; +import javax.validation.Valid; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java index a91ce9b1713f..3b322d1bb754 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -22,6 +23,7 @@ public class Pet { private Long id = null; @ApiModelProperty(value = "") + @Valid private Category category = null; @ApiModelProperty(example = "doggie", required = true, value = "") @@ -31,6 +33,7 @@ public class Pet { private List photoUrls = new ArrayList(); @ApiModelProperty(value = "") + @Valid private List tags = null; @@ -68,7 +71,7 @@ public static StatusEnum fromValue(String v) { @ApiModelProperty(value = "pet status in the store") /** - * pet status in the store + * pet status in the store **/ private StatusEnum status = null; /** diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ReadOnlyFirst.java index 144819040de9..41603bec5f63 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -1,6 +1,7 @@ package io.swagger.model; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/SpecialModelName.java index ab33c276f21e..51f98e68822e 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/SpecialModelName.java @@ -1,6 +1,7 @@ package io.swagger.model; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java index a6497e31663a..f10842e42934 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java @@ -1,6 +1,7 @@ package io.swagger.model; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java index 62643de8aa2d..c759db2cda92 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java @@ -1,6 +1,7 @@ package io.swagger.model; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -37,7 +38,7 @@ public class User { @ApiModelProperty(value = "User Status") /** - * User Status + * User Status **/ private Integer userStatus = null; /** diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeClassnameTags123ApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeClassnameTags123ApiServiceImpl.java index ad3f555af97d..e7c9f8e52ee8 100644 --- a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeClassnameTags123ApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeClassnameTags123ApiServiceImpl.java @@ -24,6 +24,8 @@ */ public class FakeClassnameTags123ApiServiceImpl implements FakeClassnameTags123Api { /** + * To test class name in snake case + * * To test class name in snake case * */ diff --git a/samples/server/petstore/pistache-server/.swagger-codegen/VERSION b/samples/server/petstore/pistache-server/.swagger-codegen/VERSION index f9f7450d1359..096bf47efe31 100644 --- a/samples/server/petstore/pistache-server/.swagger-codegen/VERSION +++ b/samples/server/petstore/pistache-server/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/pistache-server/api/PetApi.cpp b/samples/server/petstore/pistache-server/api/PetApi.cpp index edcdc694951e..5bebe0bc7d9d 100644 --- a/samples/server/petstore/pistache-server/api/PetApi.cpp +++ b/samples/server/petstore/pistache-server/api/PetApi.cpp @@ -59,12 +59,12 @@ void PetApi::setupRoutes() { void PetApi::add_pet_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { // Getting the body param - Pet body; + Pet pet; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); - body.fromJson(request_body); - this->add_pet(body, response); + pet.fromJson(request_body); + this->add_pet(pet, response); } catch (std::runtime_error & e) { //send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); @@ -132,12 +132,12 @@ void PetApi::get_pet_by_id_handler(const Pistache::Rest::Request &request, Pista void PetApi::update_pet_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { // Getting the body param - Pet body; + Pet pet; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); - body.fromJson(request_body); - this->update_pet(body, response); + pet.fromJson(request_body); + this->update_pet(pet, response); } catch (std::runtime_error & e) { //send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); diff --git a/samples/server/petstore/pistache-server/api/PetApi.h b/samples/server/petstore/pistache-server/api/PetApi.h index f6326e7ac48b..fa99be222374 100644 --- a/samples/server/petstore/pistache-server/api/PetApi.h +++ b/samples/server/petstore/pistache-server/api/PetApi.h @@ -68,8 +68,8 @@ class PetApi { /// /// /// - /// Pet object that needs to be added to the store - virtual void add_pet(const Pet &body, Pistache::Http::ResponseWriter &response) = 0; + /// Pet object that needs to be added to the store + virtual void add_pet(const Pet &pet, Pistache::Http::ResponseWriter &response) = 0; /// /// Deletes a pet @@ -114,8 +114,8 @@ class PetApi { /// /// /// - /// Pet object that needs to be added to the store - virtual void update_pet(const Pet &body, Pistache::Http::ResponseWriter &response) = 0; + /// Pet object that needs to be added to the store + virtual void update_pet(const Pet &pet, Pistache::Http::ResponseWriter &response) = 0; /// /// Updates a pet in the store with form data diff --git a/samples/server/petstore/pistache-server/api/StoreApi.cpp b/samples/server/petstore/pistache-server/api/StoreApi.cpp index 3b3a969ddb40..e005a3b5c6d9 100644 --- a/samples/server/petstore/pistache-server/api/StoreApi.cpp +++ b/samples/server/petstore/pistache-server/api/StoreApi.cpp @@ -92,12 +92,12 @@ void StoreApi::get_order_by_id_handler(const Pistache::Rest::Request &request, P void StoreApi::place_order_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { // Getting the body param - Order body; + Order order; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); - body.fromJson(request_body); - this->place_order(body, response); + order.fromJson(request_body); + this->place_order(order, response); } catch (std::runtime_error & e) { //send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); diff --git a/samples/server/petstore/pistache-server/api/StoreApi.h b/samples/server/petstore/pistache-server/api/StoreApi.h index 7cf9d69b7ab4..91f1c34391c0 100644 --- a/samples/server/petstore/pistache-server/api/StoreApi.h +++ b/samples/server/petstore/pistache-server/api/StoreApi.h @@ -90,8 +90,8 @@ class StoreApi { /// /// /// - /// order placed for purchasing the pet - virtual void place_order(const Order &body, Pistache::Http::ResponseWriter &response) = 0; + /// order placed for purchasing the pet + virtual void place_order(const Order &order, Pistache::Http::ResponseWriter &response) = 0; }; diff --git a/samples/server/petstore/pistache-server/api/UserApi.cpp b/samples/server/petstore/pistache-server/api/UserApi.cpp index 6648a72d4045..a74ee1e9b9a2 100644 --- a/samples/server/petstore/pistache-server/api/UserApi.cpp +++ b/samples/server/petstore/pistache-server/api/UserApi.cpp @@ -59,12 +59,12 @@ void UserApi::setupRoutes() { void UserApi::create_user_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { // Getting the body param - User body; + User user; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); - body.fromJson(request_body); - this->create_user(body, response); + user.fromJson(request_body); + this->create_user(user, response); } catch (std::runtime_error & e) { //send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); @@ -75,12 +75,12 @@ void UserApi::create_user_handler(const Pistache::Rest::Request &request, Pistac void UserApi::create_users_with_array_input_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { // Getting the body param - User body; + User user; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); - body.fromJson(request_body); - this->create_users_with_array_input(body, response); + user.fromJson(request_body); + this->create_users_with_array_input(user, response); } catch (std::runtime_error & e) { //send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); @@ -91,12 +91,12 @@ void UserApi::create_users_with_array_input_handler(const Pistache::Rest::Reques void UserApi::create_users_with_list_input_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { // Getting the body param - User body; + User user; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); - body.fromJson(request_body); - this->create_users_with_list_input(body, response); + user.fromJson(request_body); + this->create_users_with_list_input(user, response); } catch (std::runtime_error & e) { //send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); @@ -161,12 +161,12 @@ void UserApi::update_user_handler(const Pistache::Rest::Request &request, Pistac auto username = request.param(":username").as(); // Getting the body param - User body; + User user; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); - body.fromJson(request_body); - this->update_user(username, body, response); + user.fromJson(request_body); + this->update_user(username, user, response); } catch (std::runtime_error & e) { //send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); diff --git a/samples/server/petstore/pistache-server/api/UserApi.h b/samples/server/petstore/pistache-server/api/UserApi.h index 9d6aa3bf2e1b..ad700fb52d46 100644 --- a/samples/server/petstore/pistache-server/api/UserApi.h +++ b/samples/server/petstore/pistache-server/api/UserApi.h @@ -26,7 +26,6 @@ #include "User.h" #include -#include namespace io { namespace swagger { @@ -68,8 +67,8 @@ class UserApi { /// /// This can only be done by the logged in user. /// - /// Created user object - virtual void create_user(const User &body, Pistache::Http::ResponseWriter &response) = 0; + /// Created user object + virtual void create_user(const User &user, Pistache::Http::ResponseWriter &response) = 0; /// /// Creates list of users with given input array @@ -77,8 +76,8 @@ class UserApi { /// /// /// - /// List of user object - virtual void create_users_with_array_input(const User &body, Pistache::Http::ResponseWriter &response) = 0; + /// List of user object + virtual void create_users_with_array_input(const User &user, Pistache::Http::ResponseWriter &response) = 0; /// /// Creates list of users with given input array @@ -86,8 +85,8 @@ class UserApi { /// /// /// - /// List of user object - virtual void create_users_with_list_input(const User &body, Pistache::Http::ResponseWriter &response) = 0; + /// List of user object + virtual void create_users_with_list_input(const User &user, Pistache::Http::ResponseWriter &response) = 0; /// /// Delete user @@ -104,7 +103,7 @@ class UserApi { /// /// /// - /// The name that needs to be fetched. Use user1 for testing. + /// The name that needs to be fetched. Use user1 for testing. virtual void get_user_by_name(const std::string &username, Pistache::Http::ResponseWriter &response) = 0; /// @@ -132,8 +131,8 @@ class UserApi { /// This can only be done by the logged in user. /// /// name that need to be deleted - /// Updated user object - virtual void update_user(const std::string &username, const User &body, Pistache::Http::ResponseWriter &response) = 0; + /// Updated user object + virtual void update_user(const std::string &username, const User &user, Pistache::Http::ResponseWriter &response) = 0; }; diff --git a/samples/server/petstore/pistache-server/impl/PetApiImpl.cpp b/samples/server/petstore/pistache-server/impl/PetApiImpl.cpp index 69848e0fdc6a..2d35c04b3cc8 100644 --- a/samples/server/petstore/pistache-server/impl/PetApiImpl.cpp +++ b/samples/server/petstore/pistache-server/impl/PetApiImpl.cpp @@ -23,7 +23,7 @@ PetApiImpl::PetApiImpl(Pistache::Address addr) : PetApi(addr) { } -void PetApiImpl::add_pet(const Pet &body, Pistache::Http::ResponseWriter &response) { +void PetApiImpl::add_pet(const Pet &pet, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); } void PetApiImpl::delete_pet(const int64_t &petId, const Optional &apiKey, Pistache::Http::ResponseWriter &response) { @@ -38,7 +38,7 @@ void PetApiImpl::find_pets_by_tags(const Optional &tags, Pistache:: void PetApiImpl::get_pet_by_id(const int64_t &petId, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); } -void PetApiImpl::update_pet(const Pet &body, Pistache::Http::ResponseWriter &response) { +void PetApiImpl::update_pet(const Pet &pet, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); } void PetApiImpl::update_pet_with_form(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter &response){ diff --git a/samples/server/petstore/pistache-server/impl/PetApiImpl.h b/samples/server/petstore/pistache-server/impl/PetApiImpl.h index 1d05897194e7..511864a7c1b3 100644 --- a/samples/server/petstore/pistache-server/impl/PetApiImpl.h +++ b/samples/server/petstore/pistache-server/impl/PetApiImpl.h @@ -43,12 +43,12 @@ class PetApiImpl : public io::swagger::server::api::PetApi { PetApiImpl(Pistache::Address addr); ~PetApiImpl() { }; - void add_pet(const Pet &body, Pistache::Http::ResponseWriter &response); + void add_pet(const Pet &pet, Pistache::Http::ResponseWriter &response); void delete_pet(const int64_t &petId, const Optional &apiKey, Pistache::Http::ResponseWriter &response); void find_pets_by_status(const Optional &status, Pistache::Http::ResponseWriter &response); void find_pets_by_tags(const Optional &tags, Pistache::Http::ResponseWriter &response); void get_pet_by_id(const int64_t &petId, Pistache::Http::ResponseWriter &response); - void update_pet(const Pet &body, Pistache::Http::ResponseWriter &response); + void update_pet(const Pet &pet, Pistache::Http::ResponseWriter &response); void update_pet_with_form(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter &response); void upload_file(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter &response); diff --git a/samples/server/petstore/pistache-server/impl/StoreApiImpl.cpp b/samples/server/petstore/pistache-server/impl/StoreApiImpl.cpp index 1c03bda85f38..4d5bdde872cc 100644 --- a/samples/server/petstore/pistache-server/impl/StoreApiImpl.cpp +++ b/samples/server/petstore/pistache-server/impl/StoreApiImpl.cpp @@ -32,7 +32,7 @@ void StoreApiImpl::get_inventory(Pistache::Http::ResponseWriter &response) { void StoreApiImpl::get_order_by_id(const int64_t &orderId, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); } -void StoreApiImpl::place_order(const Order &body, Pistache::Http::ResponseWriter &response) { +void StoreApiImpl::place_order(const Order &order, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); } diff --git a/samples/server/petstore/pistache-server/impl/StoreApiImpl.h b/samples/server/petstore/pistache-server/impl/StoreApiImpl.h index 6daed72be20a..49834cdc755c 100644 --- a/samples/server/petstore/pistache-server/impl/StoreApiImpl.h +++ b/samples/server/petstore/pistache-server/impl/StoreApiImpl.h @@ -46,7 +46,7 @@ class StoreApiImpl : public io::swagger::server::api::StoreApi { void delete_order(const std::string &orderId, Pistache::Http::ResponseWriter &response); void get_inventory(Pistache::Http::ResponseWriter &response); void get_order_by_id(const int64_t &orderId, Pistache::Http::ResponseWriter &response); - void place_order(const Order &body, Pistache::Http::ResponseWriter &response); + void place_order(const Order &order, Pistache::Http::ResponseWriter &response); }; diff --git a/samples/server/petstore/pistache-server/impl/UserApiImpl.cpp b/samples/server/petstore/pistache-server/impl/UserApiImpl.cpp index 4fbd93f49d6e..a0922aef9b28 100644 --- a/samples/server/petstore/pistache-server/impl/UserApiImpl.cpp +++ b/samples/server/petstore/pistache-server/impl/UserApiImpl.cpp @@ -23,13 +23,13 @@ UserApiImpl::UserApiImpl(Pistache::Address addr) : UserApi(addr) { } -void UserApiImpl::create_user(const User &body, Pistache::Http::ResponseWriter &response) { +void UserApiImpl::create_user(const User &user, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); } -void UserApiImpl::create_users_with_array_input(const User &body, Pistache::Http::ResponseWriter &response) { +void UserApiImpl::create_users_with_array_input(const User &user, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); } -void UserApiImpl::create_users_with_list_input(const User &body, Pistache::Http::ResponseWriter &response) { +void UserApiImpl::create_users_with_list_input(const User &user, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); } void UserApiImpl::delete_user(const std::string &username, Pistache::Http::ResponseWriter &response) { @@ -44,7 +44,7 @@ void UserApiImpl::login_user(const Optional &username, const Option void UserApiImpl::logout_user(Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); } -void UserApiImpl::update_user(const std::string &username, const User &body, Pistache::Http::ResponseWriter &response) { +void UserApiImpl::update_user(const std::string &username, const User &user, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); } diff --git a/samples/server/petstore/pistache-server/impl/UserApiImpl.h b/samples/server/petstore/pistache-server/impl/UserApiImpl.h index d5f928ccafac..c10294fe97ed 100644 --- a/samples/server/petstore/pistache-server/impl/UserApiImpl.h +++ b/samples/server/petstore/pistache-server/impl/UserApiImpl.h @@ -29,7 +29,6 @@ #include "User.h" #include -#include namespace io { namespace swagger { @@ -43,14 +42,14 @@ class UserApiImpl : public io::swagger::server::api::UserApi { UserApiImpl(Pistache::Address addr); ~UserApiImpl() { }; - void create_user(const User &body, Pistache::Http::ResponseWriter &response); - void create_users_with_array_input(const User &body, Pistache::Http::ResponseWriter &response); - void create_users_with_list_input(const User &body, Pistache::Http::ResponseWriter &response); + void create_user(const User &user, Pistache::Http::ResponseWriter &response); + void create_users_with_array_input(const User &user, Pistache::Http::ResponseWriter &response); + void create_users_with_list_input(const User &user, Pistache::Http::ResponseWriter &response); void delete_user(const std::string &username, Pistache::Http::ResponseWriter &response); void get_user_by_name(const std::string &username, Pistache::Http::ResponseWriter &response); void login_user(const Optional &username, const Optional &password, Pistache::Http::ResponseWriter &response); void logout_user(Pistache::Http::ResponseWriter &response); - void update_user(const std::string &username, const User &body, Pistache::Http::ResponseWriter &response); + void update_user(const std::string &username, const User &user, Pistache::Http::ResponseWriter &response); }; diff --git a/samples/server/petstore/pistache-server/model/Order.cpp b/samples/server/petstore/pistache-server/model/Order.cpp index d1a94778deb1..bbd9c5383c7b 100644 --- a/samples/server/petstore/pistache-server/model/Order.cpp +++ b/samples/server/petstore/pistache-server/model/Order.cpp @@ -194,7 +194,7 @@ void Order::unsetStatus() { m_StatusIsSet = false; } -bool Order::getComplete() const +bool Order::isComplete() const { return m_Complete; } diff --git a/samples/server/petstore/pistache-server/model/Order.h b/samples/server/petstore/pistache-server/model/Order.h index 3872543e4594..d2512dd8f8f7 100644 --- a/samples/server/petstore/pistache-server/model/Order.h +++ b/samples/server/petstore/pistache-server/model/Order.h @@ -87,7 +87,7 @@ class Order /// /// /// - bool getComplete() const; + bool isComplete() const; void setComplete(bool value); bool completeIsSet() const; void unsetComplete(); diff --git a/samples/server/petstore/restbed/.swagger-codegen/VERSION b/samples/server/petstore/restbed/.swagger-codegen/VERSION index f9f7450d1359..096bf47efe31 100644 --- a/samples/server/petstore/restbed/.swagger-codegen/VERSION +++ b/samples/server/petstore/restbed/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.0-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/restbed/api/PetApi.cpp b/samples/server/petstore/restbed/api/PetApi.cpp index a681ad1431b1..cf65ed9b4891 100644 --- a/samples/server/petstore/restbed/api/PetApi.cpp +++ b/samples/server/petstore/restbed/api/PetApi.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/api/PetApi.h b/samples/server/petstore/restbed/api/PetApi.h index b178f31fac09..977dc27ad255 100644 --- a/samples/server/petstore/restbed/api/PetApi.h +++ b/samples/server/petstore/restbed/api/PetApi.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/api/StoreApi.cpp b/samples/server/petstore/restbed/api/StoreApi.cpp index c3a8545061db..15be337f83b4 100644 --- a/samples/server/petstore/restbed/api/StoreApi.cpp +++ b/samples/server/petstore/restbed/api/StoreApi.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/api/StoreApi.h b/samples/server/petstore/restbed/api/StoreApi.h index 5c7142cfc4f4..2ece789ddfe7 100644 --- a/samples/server/petstore/restbed/api/StoreApi.h +++ b/samples/server/petstore/restbed/api/StoreApi.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/api/UserApi.cpp b/samples/server/petstore/restbed/api/UserApi.cpp index 19ebcd66c1d6..362a126c746d 100644 --- a/samples/server/petstore/restbed/api/UserApi.cpp +++ b/samples/server/petstore/restbed/api/UserApi.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -344,9 +344,9 @@ void UserApiUserLoginResource::GET_method_handler(const std::shared_ptrset_header("X-Rate-Limit", ""); // Change second param to your header value - // Description: date in UTC when toekn expires + // Description: session->set_header("X-Expires-After", ""); // Change second param to your header value session->close(200, "successful operation", { {"Connection", "close"} }); return; diff --git a/samples/server/petstore/restbed/api/UserApi.h b/samples/server/petstore/restbed/api/UserApi.h index 4e0205f971d8..cec925c3ba26 100644 --- a/samples/server/petstore/restbed/api/UserApi.h +++ b/samples/server/petstore/restbed/api/UserApi.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ @@ -27,7 +27,6 @@ #include "User.h" #include -#include namespace io { namespace swagger { diff --git a/samples/server/petstore/restbed/git_push.sh b/samples/server/petstore/restbed/git_push.sh index 35d20f1851db..bd57362e9cac 100644 --- a/samples/server/petstore/restbed/git_push.sh +++ b/samples/server/petstore/restbed/git_push.sh @@ -36,7 +36,7 @@ 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 crediential in your environment." + 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 diff --git a/samples/server/petstore/restbed/model/ApiResponse.cpp b/samples/server/petstore/restbed/model/ApiResponse.cpp index 8335db91c2b1..180847a950a5 100644 --- a/samples/server/petstore/restbed/model/ApiResponse.cpp +++ b/samples/server/petstore/restbed/model/ApiResponse.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/model/ApiResponse.h b/samples/server/petstore/restbed/model/ApiResponse.h index 40b1d93a8cef..6c1b7b963ab5 100644 --- a/samples/server/petstore/restbed/model/ApiResponse.h +++ b/samples/server/petstore/restbed/model/ApiResponse.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/model/Category.cpp b/samples/server/petstore/restbed/model/Category.cpp index 0f3a41858abc..82a63ed7c4a5 100644 --- a/samples/server/petstore/restbed/model/Category.cpp +++ b/samples/server/petstore/restbed/model/Category.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/model/Category.h b/samples/server/petstore/restbed/model/Category.h index 83fed4a02755..99aa32ed30e8 100644 --- a/samples/server/petstore/restbed/model/Category.h +++ b/samples/server/petstore/restbed/model/Category.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/model/Order.cpp b/samples/server/petstore/restbed/model/Order.cpp index ae0888a7f96f..18758c8df3e8 100644 --- a/samples/server/petstore/restbed/model/Order.cpp +++ b/samples/server/petstore/restbed/model/Order.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/model/Order.h b/samples/server/petstore/restbed/model/Order.h index 4c44b06faeba..ef1c5ecb574b 100644 --- a/samples/server/petstore/restbed/model/Order.h +++ b/samples/server/petstore/restbed/model/Order.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/model/Pet.cpp b/samples/server/petstore/restbed/model/Pet.cpp index e1512ddb698e..3e41917e8822 100644 --- a/samples/server/petstore/restbed/model/Pet.cpp +++ b/samples/server/petstore/restbed/model/Pet.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/model/Pet.h b/samples/server/petstore/restbed/model/Pet.h index c45b9a2bda75..317e5b2719bf 100644 --- a/samples/server/petstore/restbed/model/Pet.h +++ b/samples/server/petstore/restbed/model/Pet.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/model/Tag.cpp b/samples/server/petstore/restbed/model/Tag.cpp index 5504323641d3..180daaf925ae 100644 --- a/samples/server/petstore/restbed/model/Tag.cpp +++ b/samples/server/petstore/restbed/model/Tag.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/model/Tag.h b/samples/server/petstore/restbed/model/Tag.h index 1fd64907e385..db1b13375600 100644 --- a/samples/server/petstore/restbed/model/Tag.h +++ b/samples/server/petstore/restbed/model/Tag.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/model/User.cpp b/samples/server/petstore/restbed/model/User.cpp index e34781c782bb..b3e4f027f85f 100644 --- a/samples/server/petstore/restbed/model/User.cpp +++ b/samples/server/petstore/restbed/model/User.cpp @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/restbed/model/User.h b/samples/server/petstore/restbed/model/User.h index 5a79bba992ba..19b4e72a11f7 100644 --- a/samples/server/petstore/restbed/model/User.h +++ b/samples/server/petstore/restbed/model/User.h @@ -5,7 +5,7 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * - * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. + * NOTE: This class is auto generated by the swagger code generator 3.0.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ diff --git a/samples/server/petstore/rust-server/.swagger-codegen/VERSION b/samples/server/petstore/rust-server/.swagger-codegen/VERSION index cc6612c36e05..855ff9501eb8 100644 --- a/samples/server/petstore/rust-server/.swagger-codegen/VERSION +++ b/samples/server/petstore/rust-server/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.0 \ No newline at end of file +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/Cargo.toml b/samples/server/petstore/rust-server/Cargo.toml index f44d3cc59162..6b264cc4709b 100644 --- a/samples/server/petstore/rust-server/Cargo.toml +++ b/samples/server/petstore/rust-server/Cargo.toml @@ -7,32 +7,37 @@ license = "Unlicense" [features] default = ["client", "server"] -client = ["serde_json", "serde-xml-rs", "serde_ignored", "hyper", "hyper-openssl", "uuid", "multipart"] -server = ["serde_json", "serde-xml-rs", "serde_ignored", "hyper", "iron", "router", "bodyparser", "urlencoded", "uuid", "multipart"] +client = ["serde_json", "serde_urlencoded", "serde-xml-rs", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "url", "uuid", "multipart"] +server = ["serde_json", "serde-xml-rs", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "tokio-proto", "tokio-tls", "regex", "percent-encoding", "url", "uuid", "multipart"] [dependencies] # Required by example server. # chrono = { version = "0.4", features = ["serde"] } futures = "0.1" -hyper = {version = "0.10", optional = true} -hyper-openssl = {version = "0.2", optional = true } -iron = {version = "0.5", optional = true} -swagger = "0.7" +hyper = {version = "0.11", optional = true} +hyper-tls = {version = "0.1.2", optional = true} +swagger = "0.10.0" # Not required by example server. # -bodyparser = {version = "0.7", optional = true} -url = "1.5" lazy_static = "0.2" log = "0.3.0" -multipart = {version = "0.13", optional = true} -router = {version = "0.5", optional = true} +mime = "0.3.3" +multipart = {version = "0.13.3", optional = true} +native-tls = {version = "0.1.4", optional = true} +openssl = {version = "0.9.14", optional = true} +percent-encoding = {version = "1.0.0", optional = true} +regex = {version = "0.2", optional = true} serde = "1.0" serde_derive = "1.0" serde_ignored = {version = "0.0.4", optional = true} serde_json = {version = "1.0", optional = true} -urlencoded = {version = "0.5", optional = true} +serde_urlencoded = {version = "0.5.1", optional = true} +tokio-core = {version = "0.1.6", optional = true} +tokio-proto = {version = "0.1.1", optional = true} +tokio-tls = {version = "0.1.3", optional = true, features = ["tokio-proto"]} +url = {version = "1.5", optional = true} uuid = {version = "0.5", optional = true, features = ["serde", "v4"]} # ToDo: this should be updated to point at the official crate once # https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream diff --git a/samples/server/petstore/rust-server/README.md b/samples/server/petstore/rust-server/README.md index f8bdb0ab4d1e..7080b7d2e495 100644 --- a/samples/server/petstore/rust-server/README.md +++ b/samples/server/petstore/rust-server/README.md @@ -13,7 +13,7 @@ To see how to make this your own, look here: [README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) - API version: 1.0.0 -- Build date: 2018-01-07T09:31:52.377-08:00 +- Build date: 2018-04-03T12:24:00.479+01:00 This autogenerated project defines an API crate `petstore_api` which contains: * An `Api` trait defining the API in Rust. @@ -57,6 +57,7 @@ To run a client, follow one of the following simple steps: ``` cargo run --example client TestSpecialTags +cargo run --example client TestBodyWithQueryParams cargo run --example client FakeOuterBooleanSerialize cargo run --example client FakeOuterCompositeSerialize cargo run --example client FakeOuterNumberSerialize diff --git a/samples/server/petstore/rust-server/api/swagger.yaml b/samples/server/petstore/rust-server/api/swagger.yaml index 128267b767da..3849ef4c25a5 100644 --- a/samples/server/petstore/rust-server/api/swagger.yaml +++ b/samples/server/petstore/rust-server/api/swagger.yaml @@ -70,8 +70,9 @@ paths: operation_id: "add_pet" uppercase_operation_id: "ADD_PET" path: "/pet" + PATH_ID: "PET" + hasPathParams: false HttpMethod: "Post" - httpmethod: "post" noClientExample: true put: tags: @@ -122,8 +123,9 @@ paths: operation_id: "update_pet" uppercase_operation_id: "UPDATE_PET" path: "/pet" + PATH_ID: "PET" + hasPathParams: false HttpMethod: "Put" - httpmethod: "put" noClientExample: true /pet/findByStatus: get: @@ -175,8 +177,9 @@ paths: operation_id: "find_pets_by_status" uppercase_operation_id: "FIND_PETS_BY_STATUS" path: "/pet/findByStatus" + PATH_ID: "PET_FINDBYSTATUS" + hasPathParams: false HttpMethod: "Get" - httpmethod: "get" /pet/findByTags: get: tags: @@ -224,8 +227,9 @@ paths: operation_id: "find_pets_by_tags" uppercase_operation_id: "FIND_PETS_BY_TAGS" path: "/pet/findByTags" + PATH_ID: "PET_FINDBYTAGS" + hasPathParams: false HttpMethod: "Get" - httpmethod: "get" /pet/{petId}: get: tags: @@ -270,8 +274,9 @@ paths: operation_id: "get_pet_by_id" uppercase_operation_id: "GET_PET_BY_ID" path: "/pet/:petId" + PATH_ID: "PET_PETID" + hasPathParams: true HttpMethod: "Get" - httpmethod: "get" post: tags: - "pet" @@ -319,8 +324,9 @@ paths: operation_id: "update_pet_with_form" uppercase_operation_id: "UPDATE_PET_WITH_FORM" path: "/pet/:petId" + PATH_ID: "PET_PETID" + hasPathParams: true HttpMethod: "Post" - httpmethod: "post" delete: tags: - "pet" @@ -358,8 +364,9 @@ paths: operation_id: "delete_pet" uppercase_operation_id: "DELETE_PET" path: "/pet/:petId" + PATH_ID: "PET_PETID" + hasPathParams: true HttpMethod: "Delete" - httpmethod: "delete" /pet/{petId}/uploadImage: post: tags: @@ -413,8 +420,9 @@ paths: operation_id: "upload_file" uppercase_operation_id: "UPLOAD_FILE" path: "/pet/:petId/uploadImage" + PATH_ID: "PET_PETID_UPLOADIMAGE" + hasPathParams: true HttpMethod: "Post" - httpmethod: "post" hasFile: true /store/inventory: get: @@ -444,8 +452,9 @@ paths: operation_id: "get_inventory" uppercase_operation_id: "GET_INVENTORY" path: "/store/inventory" + PATH_ID: "STORE_INVENTORY" + hasPathParams: false HttpMethod: "Get" - httpmethod: "get" /store/order: post: tags: @@ -488,8 +497,9 @@ paths: operation_id: "place_order" uppercase_operation_id: "PLACE_ORDER" path: "/store/order" + PATH_ID: "STORE_ORDER" + hasPathParams: false HttpMethod: "Post" - httpmethod: "post" noClientExample: true /store/order/{order_id}: get: @@ -536,8 +546,9 @@ paths: operation_id: "get_order_by_id" uppercase_operation_id: "GET_ORDER_BY_ID" path: "/store/order/:order_id" + PATH_ID: "STORE_ORDER_ORDER_ID" + hasPathParams: true HttpMethod: "Get" - httpmethod: "get" delete: tags: - "store" @@ -570,8 +581,9 @@ paths: operation_id: "delete_order" uppercase_operation_id: "DELETE_ORDER" path: "/store/order/:order_id" + PATH_ID: "STORE_ORDER_ORDER_ID" + hasPathParams: true HttpMethod: "Delete" - httpmethod: "delete" /user: post: tags: @@ -605,8 +617,9 @@ paths: operation_id: "create_user" uppercase_operation_id: "CREATE_USER" path: "/user" + PATH_ID: "USER" + hasPathParams: false HttpMethod: "Post" - httpmethod: "post" noClientExample: true /user/createWithArray: post: @@ -641,8 +654,9 @@ paths: operation_id: "create_users_with_array_input" uppercase_operation_id: "CREATE_USERS_WITH_ARRAY_INPUT" path: "/user/createWithArray" + PATH_ID: "USER_CREATEWITHARRAY" + hasPathParams: false HttpMethod: "Post" - httpmethod: "post" /user/createWithList: post: tags: @@ -676,8 +690,9 @@ paths: operation_id: "create_users_with_list_input" uppercase_operation_id: "CREATE_USERS_WITH_LIST_INPUT" path: "/user/createWithList" + PATH_ID: "USER_CREATEWITHLIST" + hasPathParams: false HttpMethod: "Post" - httpmethod: "post" /user/login: get: tags: @@ -716,7 +731,7 @@ paths: X-Expires-After: type: "string" format: "date-time" - description: "date in UTC when toekn expires" + description: "date in UTC when token expires" x-responseId: "SuccessfulOperation" x-uppercaseResponseId: "SUCCESSFUL_OPERATION" uppercase_operation_id: "LOGIN_USER" @@ -730,8 +745,9 @@ paths: operation_id: "login_user" uppercase_operation_id: "LOGIN_USER" path: "/user/login" + PATH_ID: "USER_LOGIN" + hasPathParams: false HttpMethod: "Get" - httpmethod: "get" /user/logout: get: tags: @@ -752,8 +768,9 @@ paths: operation_id: "logout_user" uppercase_operation_id: "LOGOUT_USER" path: "/user/logout" + PATH_ID: "USER_LOGOUT" + hasPathParams: false HttpMethod: "Get" - httpmethod: "get" /user/{username}: get: tags: @@ -767,7 +784,7 @@ paths: parameters: - name: "username" in: "path" - description: "The name that needs to be fetched. Use user1 for testing. " + description: "The name that needs to be fetched. Use user1 for testing." required: true type: "string" formatString: "\\\"{}\\\"" @@ -795,8 +812,9 @@ paths: operation_id: "get_user_by_name" uppercase_operation_id: "GET_USER_BY_NAME" path: "/user/:username" + PATH_ID: "USER_USERNAME" + hasPathParams: true HttpMethod: "Get" - httpmethod: "get" put: tags: - "user" @@ -841,8 +859,9 @@ paths: operation_id: "update_user" uppercase_operation_id: "UPDATE_USER" path: "/user/:username" + PATH_ID: "USER_USERNAME" + hasPathParams: true HttpMethod: "Put" - httpmethod: "put" noClientExample: true delete: tags: @@ -875,13 +894,15 @@ paths: operation_id: "delete_user" uppercase_operation_id: "DELETE_USER" path: "/user/:username" + PATH_ID: "USER_USERNAME" + hasPathParams: true HttpMethod: "Delete" - httpmethod: "delete" /fake_classname_test: patch: tags: - "fake_classname_tags 123#$%^" summary: "To test class name in snake case" + description: "To test class name in snake case" operationId: "testClassname" consumes: - "application/json" @@ -916,8 +937,9 @@ paths: operation_id: "test_classname" uppercase_operation_id: "TEST_CLASSNAME" path: "/fake_classname_test" + PATH_ID: "FAKE_CLASSNAME_TEST" + hasPathParams: false HttpMethod: "Patch" - httpmethod: "patch" noClientExample: true /fake: get: @@ -1042,8 +1064,9 @@ paths: operation_id: "test_enum_parameters" uppercase_operation_id: "TEST_ENUM_PARAMETERS" path: "/fake" + PATH_ID: "FAKE" + hasPathParams: false HttpMethod: "Get" - httpmethod: "get" post: tags: - "fake" @@ -1195,8 +1218,9 @@ paths: operation_id: "test_endpoint_parameters" uppercase_operation_id: "TEST_ENDPOINT_PARAMETERS" path: "/fake" + PATH_ID: "FAKE" + hasPathParams: false HttpMethod: "Post" - httpmethod: "post" patch: tags: - "fake" @@ -1234,8 +1258,9 @@ paths: operation_id: "test_client_model" uppercase_operation_id: "TEST_CLIENT_MODEL" path: "/fake" + PATH_ID: "FAKE" + hasPathParams: false HttpMethod: "Patch" - httpmethod: "patch" noClientExample: true /fake/outer/number: post: @@ -1270,8 +1295,9 @@ paths: operation_id: "fake_outer_number_serialize" uppercase_operation_id: "FAKE_OUTER_NUMBER_SERIALIZE" path: "/fake/outer/number" + PATH_ID: "FAKE_OUTER_NUMBER" + hasPathParams: false HttpMethod: "Post" - httpmethod: "post" /fake/outer/string: post: tags: @@ -1305,8 +1331,9 @@ paths: operation_id: "fake_outer_string_serialize" uppercase_operation_id: "FAKE_OUTER_STRING_SERIALIZE" path: "/fake/outer/string" + PATH_ID: "FAKE_OUTER_STRING" + hasPathParams: false HttpMethod: "Post" - httpmethod: "post" /fake/outer/boolean: post: tags: @@ -1340,8 +1367,9 @@ paths: operation_id: "fake_outer_boolean_serialize" uppercase_operation_id: "FAKE_OUTER_BOOLEAN_SERIALIZE" path: "/fake/outer/boolean" + PATH_ID: "FAKE_OUTER_BOOLEAN" + hasPathParams: false HttpMethod: "Post" - httpmethod: "post" /fake/outer/composite: post: tags: @@ -1375,8 +1403,9 @@ paths: operation_id: "fake_outer_composite_serialize" uppercase_operation_id: "FAKE_OUTER_COMPOSITE_SERIALIZE" path: "/fake/outer/composite" + PATH_ID: "FAKE_OUTER_COMPOSITE" + hasPathParams: false HttpMethod: "Post" - httpmethod: "post" /fake/jsonFormData: get: tags: @@ -1410,8 +1439,9 @@ paths: operation_id: "test_json_form_data" uppercase_operation_id: "TEST_JSON_FORM_DATA" path: "/fake/jsonFormData" + PATH_ID: "FAKE_JSONFORMDATA" + hasPathParams: false HttpMethod: "Get" - httpmethod: "get" /fake/inline-additionalProperties: post: tags: @@ -1446,8 +1476,46 @@ paths: operation_id: "test_inline_additional_properties" uppercase_operation_id: "TEST_INLINE_ADDITIONAL_PROPERTIES" path: "/fake/inline-additionalProperties" + PATH_ID: "FAKE_INLINE_ADDITIONALPROPERTIES" + hasPathParams: false HttpMethod: "Post" - httpmethod: "post" + noClientExample: true + /fake/body-with-query-params: + put: + operationId: "testBodyWithQueryParams" + consumes: + - "application/json" + parameters: + - in: "body" + name: "body" + required: true + schema: + $ref: "#/definitions/User" + uppercase_data_type: "USER" + refName: "User" + formatString: "{:?}" + example: "???" + model_key: "OuterBoolean" + uppercase_operation_id: "TEST_BODY_WITH_QUERY_PARAMS" + consumesJson: true + - name: "query" + in: "query" + required: true + type: "string" + formatString: "\\\"{}\\\"" + example: "\"query_example\".to_string()" + responses: + 200: + description: "Success" + x-responseId: "Success" + x-uppercaseResponseId: "SUCCESS" + uppercase_operation_id: "TEST_BODY_WITH_QUERY_PARAMS" + operation_id: "test_body_with_query_params" + uppercase_operation_id: "TEST_BODY_WITH_QUERY_PARAMS" + path: "/fake/body-with-query-params" + PATH_ID: "FAKE_BODY_WITH_QUERY_PARAMS" + hasPathParams: false + HttpMethod: "Put" noClientExample: true /another-fake/dummy: patch: @@ -1487,8 +1555,9 @@ paths: operation_id: "test_special_tags" uppercase_operation_id: "TEST_SPECIAL_TAGS" path: "/another-fake/dummy" + PATH_ID: "ANOTHER_FAKE_DUMMY" + hasPathParams: false HttpMethod: "Patch" - httpmethod: "patch" noClientExample: true securityDefinitions: petstore_auth: @@ -1832,6 +1901,8 @@ definitions: upperCaseName: "ENUMCLASS" Enum_Test: type: "object" + required: + - "enum_string_required" properties: enum_string: type: "string" @@ -1839,6 +1910,12 @@ definitions: - "UPPER" - "lower" - "" + enum_string_required: + type: "string" + enum: + - "UPPER" + - "lower" + - "" enum_integer: type: "integer" format: "int32" diff --git a/samples/server/petstore/rust-server/examples/client.rs b/samples/server/petstore/rust-server/examples/client.rs index e0bb1d1bc97c..2b2f69d1179c 100644 --- a/samples/server/petstore/rust-server/examples/client.rs +++ b/samples/server/petstore/rust-server/examples/client.rs @@ -8,13 +8,16 @@ extern crate swagger; #[allow(unused_extern_crates)] extern crate uuid; extern crate clap; +extern crate tokio_core; #[allow(unused_imports)] use futures::{Future, future, Stream, stream}; +use tokio_core::reactor; #[allow(unused_imports)] use petstore_api::{ApiNoContext, ContextWrapperExt, ApiError, TestSpecialTagsResponse, + TestBodyWithQueryParamsResponse, FakeOuterBooleanSerializeResponse, FakeOuterCompositeSerializeResponse, FakeOuterNumberSerializeResponse, @@ -93,18 +96,19 @@ fn main() { .help("Port to contact")) .get_matches(); + let mut core = reactor::Core::new().unwrap(); let is_https = matches.is_present("https"); let base_url = format!("{}://{}:{}", if is_https { "https" } else { "http" }, matches.value_of("host").unwrap(), matches.value_of("port").unwrap()); - let client = if is_https { + let client = if matches.is_present("https") { // Using Simple HTTPS - petstore_api::Client::try_new_https(&base_url, "examples/ca.pem") + petstore_api::Client::try_new_https(core.handle(), &base_url, "examples/ca.pem") .expect("Failed to create HTTPS client") } else { // Using HTTP - petstore_api::Client::try_new_http(&base_url) + petstore_api::Client::try_new_http(core.handle(), &base_url) .expect("Failed to create HTTP client") }; @@ -115,165 +119,171 @@ fn main() { // Disabled because there's no example. // Some("TestSpecialTags") => { - // let result = client.test_special_tags(???).wait(); + // let result = core.run(client.test_special_tags(???)); + // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // }, + + // Disabled because there's no example. + // Some("TestBodyWithQueryParams") => { + // let result = core.run(client.test_body_with_query_params(???, "query_example".to_string())); // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); // }, Some("FakeOuterBooleanSerialize") => { - let result = client.fake_outer_boolean_serialize(None).wait(); + let result = core.run(client.fake_outer_boolean_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("FakeOuterCompositeSerialize") => { - let result = client.fake_outer_composite_serialize(None).wait(); + let result = core.run(client.fake_outer_composite_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("FakeOuterNumberSerialize") => { - let result = client.fake_outer_number_serialize(None).wait(); + let result = core.run(client.fake_outer_number_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("FakeOuterStringSerialize") => { - let result = client.fake_outer_string_serialize(None).wait(); + let result = core.run(client.fake_outer_string_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, // Disabled because there's no example. // Some("TestClientModel") => { - // let result = client.test_client_model(???).wait(); + // let result = core.run(client.test_client_model(???)); // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); // }, Some("TestEndpointParameters") => { - let result = client.test_endpoint_parameters(8.14, 1.2, "pattern_without_delimiter_example".to_string(), swagger::ByteArray(Vec::from("B")), Some(56), Some(56), Some(789), Some(3.4), Some("string_example".to_string()), Some(swagger::ByteArray(Vec::from("B"))), None, None, Some("password_example".to_string()), Some("callback_example".to_string())).wait(); + let result = core.run(client.test_endpoint_parameters(8.14, 1.2, "pattern_without_delimiter_example".to_string(), swagger::ByteArray(Vec::from("B")), Some(56), Some(56), Some(789), Some(3.4), Some("string_example".to_string()), Some(swagger::ByteArray(Vec::from("B"))), None, None, Some("password_example".to_string()), Some("callback_example".to_string()))); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("TestEnumParameters") => { - let result = client.test_enum_parameters(Some(&Vec::new()), Some("enum_form_string_example".to_string()), Some(&Vec::new()), Some("enum_header_string_example".to_string()), Some(&Vec::new()), Some("enum_query_string_example".to_string()), Some(56), Some(1.2)).wait(); + let result = core.run(client.test_enum_parameters(Some(&Vec::new()), Some("enum_form_string_example".to_string()), Some(&Vec::new()), Some("enum_header_string_example".to_string()), Some(&Vec::new()), Some("enum_query_string_example".to_string()), Some(56), Some(1.2))); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, // Disabled because there's no example. // Some("TestInlineAdditionalProperties") => { - // let result = client.test_inline_additional_properties(???).wait(); + // let result = core.run(client.test_inline_additional_properties(???)); // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); // }, Some("TestJsonFormData") => { - let result = client.test_json_form_data("param_example".to_string(), "param2_example".to_string()).wait(); + let result = core.run(client.test_json_form_data("param_example".to_string(), "param2_example".to_string())); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, // Disabled because there's no example. // Some("TestClassname") => { - // let result = client.test_classname(???).wait(); + // let result = core.run(client.test_classname(???)); // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); // }, // Disabled because there's no example. // Some("AddPet") => { - // let result = client.add_pet(???).wait(); + // let result = core.run(client.add_pet(???)); // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); // }, Some("DeletePet") => { - let result = client.delete_pet(789, Some("api_key_example".to_string())).wait(); + let result = core.run(client.delete_pet(789, Some("api_key_example".to_string()))); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("FindPetsByStatus") => { - let result = client.find_pets_by_status(&Vec::new()).wait(); + let result = core.run(client.find_pets_by_status(&Vec::new())); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("FindPetsByTags") => { - let result = client.find_pets_by_tags(&Vec::new()).wait(); + let result = core.run(client.find_pets_by_tags(&Vec::new())); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("GetPetById") => { - let result = client.get_pet_by_id(789).wait(); + let result = core.run(client.get_pet_by_id(789)); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, // Disabled because there's no example. // Some("UpdatePet") => { - // let result = client.update_pet(???).wait(); + // let result = core.run(client.update_pet(???)); // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); // }, Some("UpdatePetWithForm") => { - let result = client.update_pet_with_form(789, Some("name_example".to_string()), Some("status_example".to_string())).wait(); + let result = core.run(client.update_pet_with_form(789, Some("name_example".to_string()), Some("status_example".to_string()))); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("UploadFile") => { - let result = client.upload_file(789, Some("additional_metadata_example".to_string()), Box::new(future::ok(Some(Box::new(stream::once(Ok(b"hello".to_vec()))) as Box + Send>))) as Box + Send>).wait(); + let result = core.run(client.upload_file(789, Some("additional_metadata_example".to_string()), Box::new(future::ok(Some(Box::new(stream::once(Ok(b"hello".to_vec()))) as Box + Send>))) as Box + Send>)); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("DeleteOrder") => { - let result = client.delete_order("order_id_example".to_string()).wait(); + let result = core.run(client.delete_order("order_id_example".to_string())); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("GetInventory") => { - let result = client.get_inventory().wait(); + let result = core.run(client.get_inventory()); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("GetOrderById") => { - let result = client.get_order_by_id(789).wait(); + let result = core.run(client.get_order_by_id(789)); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, // Disabled because there's no example. // Some("PlaceOrder") => { - // let result = client.place_order(???).wait(); + // let result = core.run(client.place_order(???)); // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); // }, // Disabled because there's no example. // Some("CreateUser") => { - // let result = client.create_user(???).wait(); + // let result = core.run(client.create_user(???)); // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); // }, Some("CreateUsersWithArrayInput") => { - let result = client.create_users_with_array_input(&Vec::new()).wait(); + let result = core.run(client.create_users_with_array_input(&Vec::new())); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("CreateUsersWithListInput") => { - let result = client.create_users_with_list_input(&Vec::new()).wait(); + let result = core.run(client.create_users_with_list_input(&Vec::new())); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("DeleteUser") => { - let result = client.delete_user("username_example".to_string()).wait(); + let result = core.run(client.delete_user("username_example".to_string())); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("GetUserByName") => { - let result = client.get_user_by_name("username_example".to_string()).wait(); + let result = core.run(client.get_user_by_name("username_example".to_string())); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("LoginUser") => { - let result = client.login_user("username_example".to_string(), "password_example".to_string()).wait(); + let result = core.run(client.login_user("username_example".to_string(), "password_example".to_string())); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, Some("LogoutUser") => { - let result = client.logout_user().wait(); + let result = core.run(client.logout_user()); println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); }, // Disabled because there's no example. // Some("UpdateUser") => { - // let result = client.update_user("username_example".to_string(), ???).wait(); + // let result = core.run(client.update_user("username_example".to_string(), ???)); // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); // }, diff --git a/samples/server/petstore/rust-server/examples/server.rs b/samples/server/petstore/rust-server/examples/server.rs index 85fe5c16c0db..65b48aced82d 100644 --- a/samples/server/petstore/rust-server/examples/server.rs +++ b/samples/server/petstore/rust-server/examples/server.rs @@ -6,8 +6,11 @@ // extern crate ; extern crate petstore_api; extern crate swagger; -extern crate iron; -extern crate hyper_openssl; +extern crate hyper; +extern crate openssl; +extern crate native_tls; +extern crate tokio_proto; +extern crate tokio_tls; extern crate clap; // Imports required by server library. @@ -18,18 +21,19 @@ extern crate chrono; #[macro_use] extern crate error_chain; -use hyper_openssl::OpensslServer; -use hyper_openssl::openssl::x509::X509_FILETYPE_PEM; -use hyper_openssl::openssl::ssl::{SslAcceptorBuilder, SslMethod}; -use hyper_openssl::openssl::error::ErrorStack; + +use openssl::x509::X509_FILETYPE_PEM; +use openssl::ssl::{SslAcceptorBuilder, SslMethod}; +use openssl::error::ErrorStack; +use hyper::server::Http; +use tokio_proto::TcpServer; use clap::{App, Arg}; -use iron::{Iron, Chain}; -use swagger::auth::AllowAllMiddleware; +use swagger::auth::AllowAllAuthenticator; mod server_lib; -/// Builds an SSL implementation for Simple HTTPS from some hard-coded file names -fn ssl() -> Result { +// Builds an SSL implementation for Simple HTTPS from some hard-coded file names +fn ssl() -> Result { let mut ssl = SslAcceptorBuilder::mozilla_intermediate_raw(SslMethod::tls())?; // Server authentication @@ -37,7 +41,7 @@ fn ssl() -> Result { ssl.set_certificate_chain_file("examples/server-chain.pem")?; ssl.check_private_key()?; - Ok(OpensslServer::from(ssl.build())) + Ok(ssl) } /// Create custom server, wire it to the autogenerated router, @@ -49,20 +53,22 @@ fn main() { .help("Whether to use HTTPS or not")) .get_matches(); - let server = server_lib::server().unwrap(); - let router = petstore_api::router(server); - - let mut chain = Chain::new(router); - chain.link_before(petstore_api::server::ExtractAuthData); - // add authentication middlewares into the chain here - // for the purpose of this example, pretend we have authenticated a user - chain.link_before(AllowAllMiddleware::new("cosmo")); + let service_fn = + petstore_api::server::auth::NewService::new( + AllowAllAuthenticator::new( + server_lib::NewService, + "cosmo" + ) + ); + let addr = "127.0.0.1:80".parse().expect("Failed to parse bind address"); if matches.is_present("https") { - // Using Simple HTTPS - Iron::new(chain).https("localhost:80", ssl().expect("Failed to load SSL keys")).expect("Failed to start HTTPS server"); + let ssl = ssl().expect("Failed to load SSL keys"); + let builder: native_tls::TlsAcceptorBuilder = native_tls::backend::openssl::TlsAcceptorBuilderExt::from_openssl(ssl); + let tls_acceptor = builder.build().expect("Failed to build TLS acceptor"); + TcpServer::new(tokio_tls::proto::Server::new(Http::new(), tls_acceptor), addr).serve(service_fn); } else { // Using HTTP - Iron::new(chain).http("localhost:80").expect("Failed to start HTTP server"); + TcpServer::new(Http::new(), addr).serve(service_fn); } } diff --git a/samples/server/petstore/rust-server/examples/server_lib/mod.rs b/samples/server/petstore/rust-server/examples/server_lib/mod.rs index 31964faedbea..ac79dc722b51 100644 --- a/samples/server/petstore/rust-server/examples/server_lib/mod.rs +++ b/samples/server/petstore/rust-server/examples/server_lib/mod.rs @@ -7,8 +7,20 @@ mod errors { } pub use self::errors::*; +use std::io; +use hyper; +use petstore_api; -/// Instantiate a new server. -pub fn server() -> Result { - Ok(server::Server {}) +pub struct NewService; + +impl hyper::server::NewService for NewService { + type Request = (hyper::Request, petstore_api::Context); + type Response = hyper::Response; + type Error = hyper::Error; + type Instance = petstore_api::server::Service; + + /// Instantiate a new server. + fn new_service(&self) -> io::Result { + Ok(petstore_api::server::Service::new(server::Server)) + } } diff --git a/samples/server/petstore/rust-server/examples/server_lib/server.rs b/samples/server/petstore/rust-server/examples/server_lib/server.rs index 54b01504c613..bb3a045dcbc4 100644 --- a/samples/server/petstore/rust-server/examples/server_lib/server.rs +++ b/samples/server/petstore/rust-server/examples/server_lib/server.rs @@ -7,10 +7,12 @@ use chrono; use futures::Stream; use std::collections::HashMap; use std::io::Error; + use swagger; use petstore_api::{Api, ApiError, Context, TestSpecialTagsResponse, + TestBodyWithQueryParamsResponse, FakeOuterBooleanSerializeResponse, FakeOuterCompositeSerializeResponse, FakeOuterNumberSerializeResponse, @@ -50,133 +52,140 @@ pub struct Server; impl Api for Server { /// To test special tags - fn test_special_tags(&self, body: models::Client, context: &Context) -> Box + Send> { + fn test_special_tags(&self, body: models::Client, context: &Context) -> Box> { let context = context.clone(); println!("test_special_tags({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } - fn fake_outer_boolean_serialize(&self, body: Option, context: &Context) -> Box + Send> { + fn test_body_with_query_params(&self, body: models::User, query: String, context: &Context) -> Box> { + let context = context.clone(); + println!("test_body_with_query_params({:?}, \"{}\") - X-Span-ID: {:?}", body, query, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + + fn fake_outer_boolean_serialize(&self, body: Option, context: &Context) -> Box> { let context = context.clone(); println!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } - fn fake_outer_composite_serialize(&self, body: Option, context: &Context) -> Box + Send> { + fn fake_outer_composite_serialize(&self, body: Option, context: &Context) -> Box> { let context = context.clone(); println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } - fn fake_outer_number_serialize(&self, body: Option, context: &Context) -> Box + Send> { + fn fake_outer_number_serialize(&self, body: Option, context: &Context) -> Box> { let context = context.clone(); println!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } - fn fake_outer_string_serialize(&self, body: Option, context: &Context) -> Box + Send> { + fn fake_outer_string_serialize(&self, body: Option, context: &Context) -> Box> { let context = context.clone(); println!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// To test \"client\" model - fn test_client_model(&self, body: models::Client, context: &Context) -> Box + Send> { + fn test_client_model(&self, body: models::Client, context: &Context) -> Box> { let context = context.clone(); println!("test_client_model({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &Context) -> Box + Send> { + fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &Context) -> Box> { let context = context.clone(); println!("test_endpoint_parameters({}, {}, \"{}\", {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// To test enum parameters - fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option, context: &Context) -> Box + Send> { + fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option, context: &Context) -> Box> { let context = context.clone(); println!("test_enum_parameters({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// test inline additionalProperties - fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box + Send> { + fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box> { let context = context.clone(); println!("test_inline_additional_properties({:?}) - X-Span-ID: {:?}", param, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// test json serialization of form data - fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box + Send> { + fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box> { let context = context.clone(); println!("test_json_form_data(\"{}\", \"{}\") - X-Span-ID: {:?}", param, param2, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// To test class name in snake case - fn test_classname(&self, body: models::Client, context: &Context) -> Box + Send> { + fn test_classname(&self, body: models::Client, context: &Context) -> Box> { let context = context.clone(); println!("test_classname({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Add a new pet to the store - fn add_pet(&self, body: models::Pet, context: &Context) -> Box + Send> { + fn add_pet(&self, body: models::Pet, context: &Context) -> Box> { let context = context.clone(); println!("add_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Deletes a pet - fn delete_pet(&self, pet_id: i64, api_key: Option, context: &Context) -> Box + Send> { + fn delete_pet(&self, pet_id: i64, api_key: Option, context: &Context) -> Box> { let context = context.clone(); println!("delete_pet({}, {:?}) - X-Span-ID: {:?}", pet_id, api_key, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Finds Pets by status - fn find_pets_by_status(&self, status: &Vec, context: &Context) -> Box + Send> { + fn find_pets_by_status(&self, status: &Vec, context: &Context) -> Box> { let context = context.clone(); println!("find_pets_by_status({:?}) - X-Span-ID: {:?}", status, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Finds Pets by tags - fn find_pets_by_tags(&self, tags: &Vec, context: &Context) -> Box + Send> { + fn find_pets_by_tags(&self, tags: &Vec, context: &Context) -> Box> { let context = context.clone(); println!("find_pets_by_tags({:?}) - X-Span-ID: {:?}", tags, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Find pet by ID - fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box + Send> { + fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box> { let context = context.clone(); println!("get_pet_by_id({}) - X-Span-ID: {:?}", pet_id, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Update an existing pet - fn update_pet(&self, body: models::Pet, context: &Context) -> Box + Send> { + fn update_pet(&self, body: models::Pet, context: &Context) -> Box> { let context = context.clone(); println!("update_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Updates a pet in the store with form data - fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &Context) -> Box + Send> { + fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &Context) -> Box> { let context = context.clone(); println!("update_pet_with_form({}, {:?}, {:?}) - X-Span-ID: {:?}", pet_id, name, status, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// uploads an image - fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box + Send> { + fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box> { let context = context.clone(); println!("upload_file({}, {:?}, ) - X-Span-ID: {:?}", pet_id, additional_metadata, context.x_span_id.unwrap_or(String::from("")).clone()); let _ = file; //Suppresses unused param warning @@ -184,84 +193,84 @@ impl Api for Server { } /// Delete purchase order by ID - fn delete_order(&self, order_id: String, context: &Context) -> Box + Send> { + fn delete_order(&self, order_id: String, context: &Context) -> Box> { let context = context.clone(); println!("delete_order(\"{}\") - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Returns pet inventories by status - fn get_inventory(&self, context: &Context) -> Box + Send> { + fn get_inventory(&self, context: &Context) -> Box> { let context = context.clone(); println!("get_inventory() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Find purchase order by ID - fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box + Send> { + fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box> { let context = context.clone(); println!("get_order_by_id({}) - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Place an order for a pet - fn place_order(&self, body: models::Order, context: &Context) -> Box + Send> { + fn place_order(&self, body: models::Order, context: &Context) -> Box> { let context = context.clone(); println!("place_order({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Create user - fn create_user(&self, body: models::User, context: &Context) -> Box + Send> { + fn create_user(&self, body: models::User, context: &Context) -> Box> { let context = context.clone(); println!("create_user({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Creates list of users with given input array - fn create_users_with_array_input(&self, body: &Vec, context: &Context) -> Box + Send> { + fn create_users_with_array_input(&self, body: &Vec, context: &Context) -> Box> { let context = context.clone(); println!("create_users_with_array_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Creates list of users with given input array - fn create_users_with_list_input(&self, body: &Vec, context: &Context) -> Box + Send> { + fn create_users_with_list_input(&self, body: &Vec, context: &Context) -> Box> { let context = context.clone(); println!("create_users_with_list_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Delete user - fn delete_user(&self, username: String, context: &Context) -> Box + Send> { + fn delete_user(&self, username: String, context: &Context) -> Box> { let context = context.clone(); println!("delete_user(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Get user by user name - fn get_user_by_name(&self, username: String, context: &Context) -> Box + Send> { + fn get_user_by_name(&self, username: String, context: &Context) -> Box> { let context = context.clone(); println!("get_user_by_name(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Logs user into the system - fn login_user(&self, username: String, password: String, context: &Context) -> Box + Send> { + fn login_user(&self, username: String, password: String, context: &Context) -> Box> { let context = context.clone(); println!("login_user(\"{}\", \"{}\") - X-Span-ID: {:?}", username, password, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Logs out current logged in user session - fn logout_user(&self, context: &Context) -> Box + Send> { + fn logout_user(&self, context: &Context) -> Box> { let context = context.clone(); println!("logout_user() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) } /// Updated user - fn update_user(&self, username: String, body: models::User, context: &Context) -> Box + Send> { + fn update_user(&self, username: String, body: models::User, context: &Context) -> Box> { let context = context.clone(); println!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, body, context.x_span_id.unwrap_or(String::from("")).clone()); Box::new(futures::failed("Generic failure".into())) diff --git a/samples/server/petstore/rust-server/src/client.rs b/samples/server/petstore/rust-server/src/client.rs deleted file mode 100644 index 648ba2dd3b3e..000000000000 --- a/samples/server/petstore/rust-server/src/client.rs +++ /dev/null @@ -1,1992 +0,0 @@ -#![allow(unused_extern_crates)] -extern crate hyper_openssl; -extern crate chrono; -extern crate url; -extern crate multipart; - -use multipart::client::lazy::Multipart; -use hyper; -use hyper::client::IntoUrl; -use hyper::mime; -use hyper::header::{Headers, ContentType}; -use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; -use hyper::Url; -use self::hyper_openssl::openssl; -use self::url::percent_encoding::{utf8_percent_encode, PATH_SEGMENT_ENCODE_SET, QUERY_ENCODE_SET}; -use futures; -use futures::{Future, Stream}; -use futures::{future, stream}; -use std::borrow::Cow; -use std::io::{Read, Error}; -use std::error; -use std::fmt; -use std::path::Path; -use std::sync::Arc; -use std::str; - -use mimetypes; - -use serde_json; -use serde_xml_rs; - -#[allow(unused_imports)] -use std::collections::{HashMap, BTreeMap}; -#[allow(unused_imports)] -use swagger; - -use swagger::{Context, ApiError, XSpanId}; - -use {Api, - TestSpecialTagsResponse, - FakeOuterBooleanSerializeResponse, - FakeOuterCompositeSerializeResponse, - FakeOuterNumberSerializeResponse, - FakeOuterStringSerializeResponse, - TestClientModelResponse, - TestEndpointParametersResponse, - TestEnumParametersResponse, - TestInlineAdditionalPropertiesResponse, - TestJsonFormDataResponse, - TestClassnameResponse, - AddPetResponse, - DeletePetResponse, - FindPetsByStatusResponse, - FindPetsByTagsResponse, - GetPetByIdResponse, - UpdatePetResponse, - UpdatePetWithFormResponse, - UploadFileResponse, - DeleteOrderResponse, - GetInventoryResponse, - GetOrderByIdResponse, - PlaceOrderResponse, - CreateUserResponse, - CreateUsersWithArrayInputResponse, - CreateUsersWithListInputResponse, - DeleteUserResponse, - GetUserByNameResponse, - LoginUserResponse, - LogoutUserResponse, - UpdateUserResponse - }; -use models; - -/// Convert input into a base path, e.g. "http://example:123". Also checks the scheme as it goes. -fn into_base_path(input: T, correct_scheme: Option<&'static str>) -> Result { - // First convert to Url, since a base path is a subset of Url. - let url = input.into_url()?; - - let scheme = url.scheme(); - - // Check the scheme if necessary - if let Some(correct_scheme) = correct_scheme { - if scheme != correct_scheme { - return Err(ClientInitError::InvalidScheme); - } - } - - let host = url.host().ok_or_else(|| ClientInitError::MissingHost)?; - let port = url.port().map(|x| format!(":{}", x)).unwrap_or_default(); - Ok(format!("{}://{}{}", scheme, host, port)) -} - -/// A client that implements the API by making HTTP calls out to a server. -#[derive(Clone)] -pub struct Client { - base_path: String, - hyper_client: Arc hyper::client::Client + Sync + Send>, -} - -impl fmt::Debug for Client { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Client {{ base_path: {} }}", self.base_path) - } -} - -impl Client { - pub fn try_new_http(base_path: T) -> Result - where T: IntoUrl - { - Ok(Client { - base_path: into_base_path(base_path, Some("http"))?, - hyper_client: Arc::new(hyper::client::Client::new), - }) - } - - pub fn try_new_https(base_path: T, - ca_certificate: CA) - -> Result - where T: IntoUrl, - CA: AsRef - { - let ca_certificate = ca_certificate.as_ref().to_owned(); - - let https_hyper_client = move || { - // SSL implementation - let mut ssl = openssl::ssl::SslConnectorBuilder::new(openssl::ssl::SslMethod::tls()).unwrap(); - - // Server authentication - ssl.set_ca_file(ca_certificate.clone()).unwrap(); - - let ssl = hyper_openssl::OpensslClient::from(ssl.build()); - let connector = hyper::net::HttpsConnector::new(ssl); - hyper::client::Client::with_connector(connector) - }; - - Ok(Client { - base_path: into_base_path(base_path, Some("https"))?, - hyper_client: Arc::new(https_hyper_client), - }) - } - - pub fn try_new_https_mutual(base_path: T, - ca_certificate: CA, - client_key: K, - client_certificate: C) - -> Result - where T: IntoUrl, - CA: AsRef, - K: AsRef, - C: AsRef - { - let ca_certificate = ca_certificate.as_ref().to_owned(); - let client_key = client_key.as_ref().to_owned(); - let client_certificate = client_certificate.as_ref().to_owned(); - - let https_mutual_hyper_client = move || { - // SSL implementation - let mut ssl = openssl::ssl::SslConnectorBuilder::new(openssl::ssl::SslMethod::tls()).unwrap(); - - // Server authentication - ssl.set_ca_file(ca_certificate.clone()).unwrap(); - - // Client authentication - ssl.set_private_key_file(client_key.clone(), openssl::x509::X509_FILETYPE_PEM).unwrap(); - ssl.set_certificate_chain_file(client_certificate.clone()).unwrap(); - ssl.check_private_key().unwrap(); - - let ssl = hyper_openssl::OpensslClient::from(ssl.build()); - let connector = hyper::net::HttpsConnector::new(ssl); - hyper::client::Client::with_connector(connector) - }; - - Ok(Client { - base_path: into_base_path(base_path, Some("https"))?, - hyper_client: Arc::new(https_mutual_hyper_client) - }) - } - - /// Constructor for creating a `Client` by passing in a pre-made `hyper` client. - /// - /// One should avoid relying on this function if possible, since it adds a dependency on the underlying transport - /// implementation, which it would be better to abstract away. Therefore, using this function may lead to a loss of - /// code generality, which may make it harder to move the application to a serverless environment, for example. - /// - /// The reason for this function's existence is to support legacy test code, which did mocking at the hyper layer. - /// This is not a recommended way to write new tests. If other reasons are found for using this function, they - /// should be mentioned here. - pub fn try_new_with_hyper_client(base_path: T, - hyper_client: Arc hyper::client::Client + Sync + Send>) - -> Result - where T: IntoUrl - { - Ok(Client { - base_path: into_base_path(base_path, None)?, - hyper_client: hyper_client - }) - } -} - -impl Api for Client { - - fn test_special_tags(&self, param_body: models::Client, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/another-fake/dummy", - self.base_path - ); - - - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Patch, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = request.body(&body); - - custom_headers.set(ContentType(mimetypes::requests::TEST_SPECIAL_TAGS.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(&buf)?; - - Ok(TestSpecialTagsResponse::SuccessfulOperation(body)) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn fake_outer_boolean_serialize(&self, param_body: Option, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/fake/outer/boolean", - self.base_path - ); - - let body = param_body.map(|ref body| { - - serde_json::to_string(body).expect("impossible to fail to serialize") - }); - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = match body { - Some(ref body) => request.body(body), - None => request, - }; - - custom_headers.set(ContentType(mimetypes::requests::FAKE_OUTER_BOOLEAN_SERIALIZE.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(&buf)?; - - Ok(FakeOuterBooleanSerializeResponse::OutputBoolean(body)) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn fake_outer_composite_serialize(&self, param_body: Option, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/fake/outer/composite", - self.base_path - ); - - let body = param_body.map(|ref body| { - - serde_json::to_string(body).expect("impossible to fail to serialize") - }); - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = match body { - Some(ref body) => request.body(body), - None => request, - }; - - custom_headers.set(ContentType(mimetypes::requests::FAKE_OUTER_COMPOSITE_SERIALIZE.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(&buf)?; - - Ok(FakeOuterCompositeSerializeResponse::OutputComposite(body)) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn fake_outer_number_serialize(&self, param_body: Option, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/fake/outer/number", - self.base_path - ); - - let body = param_body.map(|ref body| { - - serde_json::to_string(body).expect("impossible to fail to serialize") - }); - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = match body { - Some(ref body) => request.body(body), - None => request, - }; - - custom_headers.set(ContentType(mimetypes::requests::FAKE_OUTER_NUMBER_SERIALIZE.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(&buf)?; - - Ok(FakeOuterNumberSerializeResponse::OutputNumber(body)) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn fake_outer_string_serialize(&self, param_body: Option, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/fake/outer/string", - self.base_path - ); - - let body = param_body.map(|ref body| { - - serde_json::to_string(body).expect("impossible to fail to serialize") - }); - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = match body { - Some(ref body) => request.body(body), - None => request, - }; - - custom_headers.set(ContentType(mimetypes::requests::FAKE_OUTER_STRING_SERIALIZE.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(&buf)?; - - Ok(FakeOuterStringSerializeResponse::OutputString(body)) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn test_client_model(&self, param_body: models::Client, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/fake", - self.base_path - ); - - - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Patch, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = request.body(&body); - - custom_headers.set(ContentType(mimetypes::requests::TEST_CLIENT_MODEL.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(&buf)?; - - Ok(TestClientModelResponse::SuccessfulOperation(body)) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn test_endpoint_parameters(&self, param_number: f64, param_double: f64, param_pattern_without_delimiter: String, param_byte: swagger::ByteArray, param_integer: Option, param_int32: Option, param_int64: Option, param_float: Option, param_string: Option, param_binary: Option, param_date: Option>, param_date_time: Option>, param_password: Option, param_callback: Option, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/fake", - self.base_path - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 400 => { - - - Ok(TestEndpointParametersResponse::InvalidUsernameSupplied) - }, - 404 => { - - - Ok(TestEndpointParametersResponse::UserNotFound) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn test_enum_parameters(&self, param_enum_form_string_array: Option<&Vec>, param_enum_form_string: Option, param_enum_header_string_array: Option<&Vec>, param_enum_header_string: Option, param_enum_query_string_array: Option<&Vec>, param_enum_query_string: Option, param_enum_query_integer: Option, param_enum_query_double: Option, context: &Context) -> Box + Send> { - - // Query parameters - let query_enum_query_string_array = param_enum_query_string_array.map_or_else(String::new, |query| format!("enum_query_string_array={enum_query_string_array}&", enum_query_string_array=query.join(","))); - let query_enum_query_string = param_enum_query_string.map_or_else(String::new, |query| format!("enum_query_string={enum_query_string}&", enum_query_string=query.to_string())); - let query_enum_query_integer = param_enum_query_integer.map_or_else(String::new, |query| format!("enum_query_integer={enum_query_integer}&", enum_query_integer=query.to_string())); - - - let url = format!( - "{}/v2/fake?{enum_query_string_array}{enum_query_string}{enum_query_integer}", - self.base_path, - enum_query_string_array=utf8_percent_encode(&query_enum_query_string_array, QUERY_ENCODE_SET), - enum_query_string=utf8_percent_encode(&query_enum_query_string, QUERY_ENCODE_SET), - enum_query_integer=utf8_percent_encode(&query_enum_query_integer, QUERY_ENCODE_SET) - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Get, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - // Header parameters - header! { (RequestEnumHeaderStringArray, "enum_header_string_array") => (String)* } - param_enum_header_string_array.map(|header| custom_headers.set(RequestEnumHeaderStringArray(header.clone()))); - header! { (RequestEnumHeaderString, "enum_header_string") => [String] } - param_enum_header_string.map(|header| custom_headers.set(RequestEnumHeaderString(header))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 400 => { - - - Ok(TestEnumParametersResponse::InvalidRequest) - }, - 404 => { - - - Ok(TestEnumParametersResponse::NotFound) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn test_inline_additional_properties(&self, param_param: object, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/fake/inline-additionalProperties", - self.base_path - ); - - - let body = serde_json::to_string(¶m_param).expect("impossible to fail to serialize"); - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = request.body(&body); - - custom_headers.set(ContentType(mimetypes::requests::TEST_INLINE_ADDITIONAL_PROPERTIES.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - - - Ok(TestInlineAdditionalPropertiesResponse::SuccessfulOperation) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn test_json_form_data(&self, param_param: String, param_param2: String, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/fake/jsonFormData", - self.base_path - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Get, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - - - Ok(TestJsonFormDataResponse::SuccessfulOperation) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn test_classname(&self, param_body: models::Client, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/fake_classname_test", - self.base_path - ); - - - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Patch, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = request.body(&body); - - custom_headers.set(ContentType(mimetypes::requests::TEST_CLASSNAME.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(&buf)?; - - Ok(TestClassnameResponse::SuccessfulOperation(body)) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn add_pet(&self, param_body: models::Pet, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/pet", - self.base_path - ); - - - let body = serde_xml_rs::to_string(¶m_body).expect("impossible to fail to serialize"); - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = request.body(&body); - - custom_headers.set(ContentType(mimetypes::requests::ADD_PET.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 405 => { - - - Ok(AddPetResponse::InvalidInput) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn delete_pet(&self, param_pet_id: i64, param_api_key: Option, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/pet/{petId}", - self.base_path, petId=utf8_percent_encode(¶m_pet_id.to_string(), PATH_SEGMENT_ENCODE_SET) - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Delete, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - // Header parameters - header! { (RequestApiKey, "api_key") => [String] } - param_api_key.map(|header| custom_headers.set(RequestApiKey(header))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 400 => { - - - Ok(DeletePetResponse::InvalidPetValue) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn find_pets_by_status(&self, param_status: &Vec, context: &Context) -> Box + Send> { - - // Query parameters - let query_status = format!("status={status}&", status=param_status.join(",")); - - - let url = format!( - "{}/v2/pet/findByStatus?{status}", - self.base_path, - status=utf8_percent_encode(&query_status, QUERY_ENCODE_SET) - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Get, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - // ToDo: this will move to swagger-rs and become a standard From conversion trait - // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream - let body = serde_xml_rs::from_str::>(&buf) - .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; - - Ok(FindPetsByStatusResponse::SuccessfulOperation(body)) - }, - 400 => { - - - Ok(FindPetsByStatusResponse::InvalidStatusValue) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn find_pets_by_tags(&self, param_tags: &Vec, context: &Context) -> Box + Send> { - - // Query parameters - let query_tags = format!("tags={tags}&", tags=param_tags.join(",")); - - - let url = format!( - "{}/v2/pet/findByTags?{tags}", - self.base_path, - tags=utf8_percent_encode(&query_tags, QUERY_ENCODE_SET) - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Get, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - // ToDo: this will move to swagger-rs and become a standard From conversion trait - // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream - let body = serde_xml_rs::from_str::>(&buf) - .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; - - Ok(FindPetsByTagsResponse::SuccessfulOperation(body)) - }, - 400 => { - - - Ok(FindPetsByTagsResponse::InvalidTagValue) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn get_pet_by_id(&self, param_pet_id: i64, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/pet/{petId}", - self.base_path, petId=utf8_percent_encode(¶m_pet_id.to_string(), PATH_SEGMENT_ENCODE_SET) - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Get, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - // ToDo: this will move to swagger-rs and become a standard From conversion trait - // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream - let body = serde_xml_rs::from_str::(&buf) - .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; - - Ok(GetPetByIdResponse::SuccessfulOperation(body)) - }, - 400 => { - - - Ok(GetPetByIdResponse::InvalidIDSupplied) - }, - 404 => { - - - Ok(GetPetByIdResponse::PetNotFound) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn update_pet(&self, param_body: models::Pet, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/pet", - self.base_path - ); - - - let body = serde_xml_rs::to_string(¶m_body).expect("impossible to fail to serialize"); - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Put, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = request.body(&body); - - custom_headers.set(ContentType(mimetypes::requests::UPDATE_PET.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 400 => { - - - Ok(UpdatePetResponse::InvalidIDSupplied) - }, - 404 => { - - - Ok(UpdatePetResponse::PetNotFound) - }, - 405 => { - - - Ok(UpdatePetResponse::ValidationException) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn update_pet_with_form(&self, param_pet_id: i64, param_name: Option, param_status: Option, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/pet/{petId}", - self.base_path, petId=utf8_percent_encode(¶m_pet_id.to_string(), PATH_SEGMENT_ENCODE_SET) - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 405 => { - - - Ok(UpdatePetWithFormResponse::InvalidInput) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn upload_file(&self, param_pet_id: i64, param_additional_metadata: Option, param_file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/pet/{petId}/uploadImage", - self.base_path, petId=utf8_percent_encode(¶m_pet_id.to_string(), PATH_SEGMENT_ENCODE_SET) - ); - - // Form data body - let mut multipart = Multipart::new(); - - if let Ok(Some(param_file)) = param_file.wait() { - match convert_stream_to_string(param_file) { - Ok(param_file) => { - // Add file to multipart form. - multipart.add_text("file", param_file); - }, - Err(err) => return Box::new(futures::done(Err(err))), - } - } - - let mut fields = match multipart.prepare() { - Ok(fields) => fields, - Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build request: {}", err))))), - }; - - let mut body_string = String::new(); - let body = fields.to_body().read_to_string(&mut body_string); - let boundary = fields.boundary(); - let multipart_header = Mime(TopLevel::Multipart, SubLevel::FormData, vec![(Attr::Boundary, Value::Ext(boundary.to_string()))]); - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - let request = request.header(ContentType(multipart_header)) - .body(&body_string); - - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(&buf)?; - - Ok(UploadFileResponse::SuccessfulOperation(body)) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - // Helper function to convert a Stream into a String. The String can then be used to build the HTTP body. - fn convert_stream_to_string(stream: Box, Error=Error> + Send>) -> Result { - - stream.fold(Vec::new(), |mut body, chunk| { - body.extend(chunk.iter()); - future::ok::,Error>(body) - }).wait() - .map_err(|e| ApiError(format!("Unable to fold stream: {}", e))) - .and_then(|body| String::from_utf8(body) - .map_err(|e| ApiError(format!("Failed to convert utf8 stream to String: {}", e)))) - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn delete_order(&self, param_order_id: String, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/store/order/{order_id}", - self.base_path, order_id=utf8_percent_encode(¶m_order_id.to_string(), PATH_SEGMENT_ENCODE_SET) - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Delete, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 400 => { - - - Ok(DeleteOrderResponse::InvalidIDSupplied) - }, - 404 => { - - - Ok(DeleteOrderResponse::OrderNotFound) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn get_inventory(&self, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/store/inventory", - self.base_path - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Get, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(&buf)?; - - Ok(GetInventoryResponse::SuccessfulOperation(body)) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn get_order_by_id(&self, param_order_id: i64, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/store/order/{order_id}", - self.base_path, order_id=utf8_percent_encode(¶m_order_id.to_string(), PATH_SEGMENT_ENCODE_SET) - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Get, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - // ToDo: this will move to swagger-rs and become a standard From conversion trait - // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream - let body = serde_xml_rs::from_str::(&buf) - .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; - - Ok(GetOrderByIdResponse::SuccessfulOperation(body)) - }, - 400 => { - - - Ok(GetOrderByIdResponse::InvalidIDSupplied) - }, - 404 => { - - - Ok(GetOrderByIdResponse::OrderNotFound) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn place_order(&self, param_body: models::Order, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/store/order", - self.base_path - ); - - - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = request.body(&body); - - custom_headers.set(ContentType(mimetypes::requests::PLACE_ORDER.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - // ToDo: this will move to swagger-rs and become a standard From conversion trait - // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream - let body = serde_xml_rs::from_str::(&buf) - .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; - - Ok(PlaceOrderResponse::SuccessfulOperation(body)) - }, - 400 => { - - - Ok(PlaceOrderResponse::InvalidOrder) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn create_user(&self, param_body: models::User, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/user", - self.base_path - ); - - - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = request.body(&body); - - custom_headers.set(ContentType(mimetypes::requests::CREATE_USER.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 0 => { - - - Ok(CreateUserResponse::SuccessfulOperation) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn create_users_with_array_input(&self, param_body: &Vec, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/user/createWithArray", - self.base_path - ); - - - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = request.body(&body); - - custom_headers.set(ContentType(mimetypes::requests::CREATE_USERS_WITH_ARRAY_INPUT.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 0 => { - - - Ok(CreateUsersWithArrayInputResponse::SuccessfulOperation) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn create_users_with_list_input(&self, param_body: &Vec, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/user/createWithList", - self.base_path - ); - - - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Post, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = request.body(&body); - - custom_headers.set(ContentType(mimetypes::requests::CREATE_USERS_WITH_LIST_INPUT.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 0 => { - - - Ok(CreateUsersWithListInputResponse::SuccessfulOperation) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn delete_user(&self, param_username: String, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/user/{username}", - self.base_path, username=utf8_percent_encode(¶m_username.to_string(), PATH_SEGMENT_ENCODE_SET) - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Delete, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 400 => { - - - Ok(DeleteUserResponse::InvalidUsernameSupplied) - }, - 404 => { - - - Ok(DeleteUserResponse::UserNotFound) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn get_user_by_name(&self, param_username: String, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/user/{username}", - self.base_path, username=utf8_percent_encode(¶m_username.to_string(), PATH_SEGMENT_ENCODE_SET) - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Get, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - // ToDo: this will move to swagger-rs and become a standard From conversion trait - // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream - let body = serde_xml_rs::from_str::(&buf) - .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; - - Ok(GetUserByNameResponse::SuccessfulOperation(body)) - }, - 400 => { - - - Ok(GetUserByNameResponse::InvalidUsernameSupplied) - }, - 404 => { - - - Ok(GetUserByNameResponse::UserNotFound) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn login_user(&self, param_username: String, param_password: String, context: &Context) -> Box + Send> { - - // Query parameters - let query_username = format!("username={username}&", username=param_username.to_string()); - let query_password = format!("password={password}&", password=param_password.to_string()); - - - let url = format!( - "{}/v2/user/login?{username}{password}", - self.base_path, - username=utf8_percent_encode(&query_username, QUERY_ENCODE_SET), - password=utf8_percent_encode(&query_password, QUERY_ENCODE_SET) - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Get, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 200 => { - let mut buf = String::new(); - response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - // ToDo: this will move to swagger-rs and become a standard From conversion trait - // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream - let body = serde_xml_rs::from_str::(&buf) - .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; - header! { (ResponseXRateLimit, "X-Rate-Limit") => [i32] } - let response_x_rate_limit = response.headers.get::().ok_or_else(|| "Required response header X-Rate-Limit for response 200 was not found.")?; - header! { (ResponseXExpiresAfter, "X-Expires-After") => [chrono::DateTime] } - let response_x_expires_after = response.headers.get::().ok_or_else(|| "Required response header X-Expires-After for response 200 was not found.")?; - - Ok(LoginUserResponse::SuccessfulOperation{ body: body, x_rate_limit: response_x_rate_limit.0.clone(), x_expires_after: response_x_expires_after.0.clone() }) - }, - 400 => { - - - Ok(LoginUserResponse::InvalidUsername) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn logout_user(&self, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/user/logout", - self.base_path - ); - - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Get, &url); - let mut custom_headers = hyper::header::Headers::new(); - - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 0 => { - - - Ok(LogoutUserResponse::SuccessfulOperation) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - - fn update_user(&self, param_username: String, param_body: models::User, context: &Context) -> Box + Send> { - - - let url = format!( - "{}/v2/user/{username}", - self.base_path, username=utf8_percent_encode(¶m_username.to_string(), PATH_SEGMENT_ENCODE_SET) - ); - - - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - - let hyper_client = (self.hyper_client)(); - let request = hyper_client.request(hyper::method::Method::Put, &url); - let mut custom_headers = hyper::header::Headers::new(); - - let request = request.body(&body); - - custom_headers.set(ContentType(mimetypes::requests::UPDATE_USER.clone())); - context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); - - - let request = request.headers(custom_headers); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn parse_response(mut response: hyper::client::response::Response) -> Result { - match response.status.to_u16() { - 400 => { - - - Ok(UpdateUserResponse::InvalidUserSupplied) - }, - 404 => { - - - Ok(UpdateUserResponse::UserNotFound) - }, - code => { - let mut buf = [0; 100]; - let debug_body = match response.read(&mut buf) { - Ok(len) => match str::from_utf8(&buf[..len]) { - Ok(body) => Cow::from(body), - Err(_) => Cow::from(format!("", &buf[..len].to_vec())), - }, - Err(e) => Cow::from(format!("", e)), - }; - Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", - code, - response.headers, - debug_body))) - } - } - } - - let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); - Box::new(futures::done(result)) - } - -} - -#[derive(Debug)] -pub enum ClientInitError { - InvalidScheme, - InvalidUrl(hyper::error::ParseError), - MissingHost, - SslError(openssl::error::ErrorStack) -} - -impl From for ClientInitError { - fn from(err: hyper::error::ParseError) -> ClientInitError { - ClientInitError::InvalidUrl(err) - } -} - -impl From for ClientInitError { - fn from(err: openssl::error::ErrorStack) -> ClientInitError { - ClientInitError::SslError(err) - } -} - -impl fmt::Display for ClientInitError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - (self as &fmt::Debug).fmt(f) - } -} - -impl error::Error for ClientInitError { - fn description(&self) -> &str { - "Failed to produce a hyper client." - } -} diff --git a/samples/server/petstore/rust-server/src/client/mod.rs b/samples/server/petstore/rust-server/src/client/mod.rs new file mode 100644 index 000000000000..645907ba2d10 --- /dev/null +++ b/samples/server/petstore/rust-server/src/client/mod.rs @@ -0,0 +1,2783 @@ +#![allow(unused_extern_crates)] +extern crate tokio_core; +extern crate native_tls; +extern crate hyper_tls; +extern crate openssl; +extern crate mime; +extern crate chrono; +extern crate url; +extern crate multipart; +extern crate serde_urlencoded; + + +use self::multipart::client::lazy::Multipart; +use hyper; +use hyper::header::{Headers, ContentType}; +use hyper::Uri; +use self::url::percent_encoding::{utf8_percent_encode, PATH_SEGMENT_ENCODE_SET, QUERY_ENCODE_SET}; +use futures; +use futures::{Future, Stream}; +use futures::{future, stream}; +use self::tokio_core::reactor::Handle; +use std::borrow::Cow; +use std::io::{Read, Error, ErrorKind}; +use std::error; +use std::fmt; +use std::path::Path; +use std::sync::Arc; +use std::str; +use std::str::FromStr; + +use mimetypes; + +use serde_json; +use serde_xml_rs; + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; + +use swagger::{Context, ApiError, XSpanId}; + +use {Api, + TestSpecialTagsResponse, + TestBodyWithQueryParamsResponse, + FakeOuterBooleanSerializeResponse, + FakeOuterCompositeSerializeResponse, + FakeOuterNumberSerializeResponse, + FakeOuterStringSerializeResponse, + TestClientModelResponse, + TestEndpointParametersResponse, + TestEnumParametersResponse, + TestInlineAdditionalPropertiesResponse, + TestJsonFormDataResponse, + TestClassnameResponse, + AddPetResponse, + DeletePetResponse, + FindPetsByStatusResponse, + FindPetsByTagsResponse, + GetPetByIdResponse, + UpdatePetResponse, + UpdatePetWithFormResponse, + UploadFileResponse, + DeleteOrderResponse, + GetInventoryResponse, + GetOrderByIdResponse, + PlaceOrderResponse, + CreateUserResponse, + CreateUsersWithArrayInputResponse, + CreateUsersWithListInputResponse, + DeleteUserResponse, + GetUserByNameResponse, + LoginUserResponse, + LogoutUserResponse, + UpdateUserResponse + }; +use models; + +/// Convert input into a base path, e.g. "http://example:123". Also checks the scheme as it goes. +fn into_base_path(input: &str, correct_scheme: Option<&'static str>) -> Result { + // First convert to Uri, since a base path is a subset of Uri. + let uri = Uri::from_str(input)?; + + let scheme = uri.scheme().ok_or(ClientInitError::InvalidScheme)?; + + // Check the scheme if necessary + if let Some(correct_scheme) = correct_scheme { + if scheme != correct_scheme { + return Err(ClientInitError::InvalidScheme); + } + } + + let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; + let port = uri.port().map(|x| format!(":{}", x)).unwrap_or_default(); + Ok(format!("{}://{}{}", scheme, host, port)) +} + +/// A client that implements the API by making HTTP calls out to a server. +#[derive(Clone)] +pub struct Client { + hyper_client: Arc Box, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>> + Sync + Send>, + handle: Arc, + base_path: String, +} + +impl fmt::Debug for Client { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Client {{ base_path: {} }}", self.base_path) + } +} + +impl Client { + + /// Create an HTTP client. + /// + /// # Arguments + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + pub fn try_new_http(handle: Handle, base_path: &str) -> Result { + let http_connector = swagger::http_connector(); + Self::try_new_with_connector::( + handle, + base_path, + Some("http"), + http_connector, + ) + } + + /// Create a client with a TLS connection to the server. + /// + /// # Arguments + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + /// * `ca_certificate` - Path to CA certificate used to authenticate the server + pub fn try_new_https( + handle: Handle, + base_path: &str, + ca_certificate: CA, + ) -> Result + where + CA: AsRef, + { + let https_connector = swagger::https_connector(ca_certificate); + Self::try_new_with_connector::>( + handle, + base_path, + Some("https"), + https_connector, + ) + } + + /// Create a client with a mutually authenticated TLS connection to the server. + /// + /// # Arguments + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + /// * `ca_certificate` - Path to CA certificate used to authenticate the server + /// * `client_key` - Path to the client private key + /// * `client_certificate` - Path to the client's public certificate associated with the private key + pub fn try_new_https_mutual( + handle: Handle, + base_path: &str, + ca_certificate: CA, + client_key: K, + client_certificate: C, + ) -> Result + where + CA: AsRef, + K: AsRef, + C: AsRef, + { + let https_connector = + swagger::https_mutual_connector(ca_certificate, client_key, client_certificate); + Self::try_new_with_connector::>( + handle, + base_path, + Some("https"), + https_connector, + ) + } + + /// Create a client with a custom implementation of hyper::client::Connect. + /// + /// Intended for use with custom implementations of connect for e.g. protocol logging + /// or similar functionality which requires wrapping the transport layer. When wrapping a TCP connection, + /// this function should be used in conjunction with + /// `swagger::{http_connector, https_connector, https_mutual_connector}`. + /// + /// For ordinary tcp connections, prefer the use of `try_new_http`, `try_new_https` + /// and `try_new_https_mutual`, to avoid introducing a dependency on the underlying transport layer. + /// + /// # Arguments + /// + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + /// * `protocol` - Which protocol to use when constructing the request url, e.g. `Some("http")` + /// * `connector_fn` - Function which returns an implementation of `hyper::client::Connect` + pub fn try_new_with_connector( + handle: Handle, + base_path: &str, + protocol: Option<&'static str>, + connector_fn: Box C + Send + Sync>, + ) -> Result + where + C: hyper::client::Connect + hyper::client::Service, + { + let hyper_client = { + move |handle: &Handle| -> Box< + hyper::client::Service< + Request = hyper::Request, + Response = hyper::Response, + Error = hyper::Error, + Future = hyper::client::FutureResponse, + >, + > { + let connector = connector_fn(handle); + Box::new(hyper::Client::configure().connector(connector).build( + handle, + )) + } + }; + + Ok(Client { + hyper_client: Arc::new(hyper_client), + handle: Arc::new(handle), + base_path: into_base_path(base_path, protocol)?, + }) + } + + /// Constructor for creating a `Client` by passing in a pre-made `hyper` client. + /// + /// One should avoid relying on this function if possible, since it adds a dependency on the underlying transport + /// implementation, which it would be better to abstract away. Therefore, using this function may lead to a loss of + /// code generality, which may make it harder to move the application to a serverless environment, for example. + /// + /// The reason for this function's existence is to support legacy test code, which did mocking at the hyper layer. + /// This is not a recommended way to write new tests. If other reasons are found for using this function, they + /// should be mentioned here. + pub fn try_new_with_hyper_client(hyper_client: Arc Box, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>> + Sync + Send>, + handle: Handle, + base_path: &str) + -> Result + { + Ok(Client { + hyper_client: hyper_client, + handle: Arc::new(handle), + base_path: into_base_path(base_path, None)?, + }) + } +} + +impl Api for Client { + + fn test_special_tags(&self, param_body: models::Client, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/another-fake/dummy", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Patch, uri); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::TEST_SPECIAL_TAGS.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + serde_json::from_str::(body) + .map_err(|e| e.into()) + + )) + .map(move |body| + TestSpecialTagsResponse::SuccessfulOperation(body) + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn test_body_with_query_params(&self, param_body: models::User, param_query: String, context: &Context) -> Box> { + + // Query parameters + let query_query = format!("query={query}&", query=param_query.to_string()); + + + let uri = format!( + "{}/v2/fake/body-with-query-params?{query}", + self.base_path, + query=utf8_percent_encode(&query_query, QUERY_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Put, uri); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::TEST_BODY_WITH_QUERY_PARAMS.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + future::ok( + TestBodyWithQueryParamsResponse::Success + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn fake_outer_boolean_serialize(&self, param_body: Option, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/fake/outer/boolean", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + let body = param_body.map(|ref body| { + + serde_json::to_string(body).expect("impossible to fail to serialize") + }); + +if let Some(body) = body { + request.set_body(body.into_bytes()); + } + + request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_BOOLEAN_SERIALIZE.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + serde_json::from_str::(body) + .map_err(|e| e.into()) + + )) + .map(move |body| + FakeOuterBooleanSerializeResponse::OutputBoolean(body) + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn fake_outer_composite_serialize(&self, param_body: Option, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/fake/outer/composite", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + let body = param_body.map(|ref body| { + + serde_json::to_string(body).expect("impossible to fail to serialize") + }); + +if let Some(body) = body { + request.set_body(body.into_bytes()); + } + + request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_COMPOSITE_SERIALIZE.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + serde_json::from_str::(body) + .map_err(|e| e.into()) + + )) + .map(move |body| + FakeOuterCompositeSerializeResponse::OutputComposite(body) + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn fake_outer_number_serialize(&self, param_body: Option, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/fake/outer/number", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + let body = param_body.map(|ref body| { + + serde_json::to_string(body).expect("impossible to fail to serialize") + }); + +if let Some(body) = body { + request.set_body(body.into_bytes()); + } + + request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_NUMBER_SERIALIZE.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + serde_json::from_str::(body) + .map_err(|e| e.into()) + + )) + .map(move |body| + FakeOuterNumberSerializeResponse::OutputNumber(body) + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn fake_outer_string_serialize(&self, param_body: Option, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/fake/outer/string", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + let body = param_body.map(|ref body| { + + serde_json::to_string(body).expect("impossible to fail to serialize") + }); + +if let Some(body) = body { + request.set_body(body.into_bytes()); + } + + request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_STRING_SERIALIZE.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + serde_json::from_str::(body) + .map_err(|e| e.into()) + + )) + .map(move |body| + FakeOuterStringSerializeResponse::OutputString(body) + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn test_client_model(&self, param_body: models::Client, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/fake", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Patch, uri); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::TEST_CLIENT_MODEL.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + serde_json::from_str::(body) + .map_err(|e| e.into()) + + )) + .map(move |body| + TestClientModelResponse::SuccessfulOperation(body) + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn test_endpoint_parameters(&self, param_number: f64, param_double: f64, param_pattern_without_delimiter: String, param_byte: swagger::ByteArray, param_integer: Option, param_int32: Option, param_int64: Option, param_float: Option, param_string: Option, param_binary: Option, param_date: Option>, param_date_time: Option>, param_password: Option, param_callback: Option, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/fake", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + let params = &[ + ("integer", param_integer.map(|param| format!("{:?}", param))), + ("int32", param_int32.map(|param| format!("{:?}", param))), + ("int64", param_int64.map(|param| format!("{:?}", param))), + ("number", Some(format!("{:?}", param_number))), + ("float", param_float.map(|param| format!("{:?}", param))), + ("double", Some(format!("{:?}", param_double))), + ("string", param_string), + ("pattern_without_delimiter", Some(param_pattern_without_delimiter)), + ("byte", Some(format!("{:?}", param_byte))), + ("binary", param_binary.map(|param| format!("{:?}", param))), + ("date", param_date.map(|param| format!("{:?}", param))), + ("dateTime", param_date_time.map(|param| format!("{:?}", param))), + ("password", param_password), + ("callback", param_callback), + ]; + let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize"); + + request.headers_mut().set(ContentType(mimetypes::requests::TEST_ENDPOINT_PARAMETERS.clone())); + request.set_body(body.into_bytes()); + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + context.auth_data.as_ref().map(|auth_data| { + if let &swagger::AuthData::Basic(ref basic_header) = auth_data { + request.headers_mut().set(hyper::header::Authorization( + basic_header.clone(), + )) + } + }); + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 400 => { + let body = response.body(); + Box::new( + + future::ok( + TestEndpointParametersResponse::InvalidUsernameSupplied + ) + ) as Box> + }, + 404 => { + let body = response.body(); + Box::new( + + future::ok( + TestEndpointParametersResponse::UserNotFound + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn test_enum_parameters(&self, param_enum_form_string_array: Option<&Vec>, param_enum_form_string: Option, param_enum_header_string_array: Option<&Vec>, param_enum_header_string: Option, param_enum_query_string_array: Option<&Vec>, param_enum_query_string: Option, param_enum_query_integer: Option, param_enum_query_double: Option, context: &Context) -> Box> { + + // Query parameters + let query_enum_query_string_array = param_enum_query_string_array.map_or_else(String::new, |query| format!("enum_query_string_array={enum_query_string_array}&", enum_query_string_array=query.join(","))); + let query_enum_query_string = param_enum_query_string.map_or_else(String::new, |query| format!("enum_query_string={enum_query_string}&", enum_query_string=query.to_string())); + let query_enum_query_integer = param_enum_query_integer.map_or_else(String::new, |query| format!("enum_query_integer={enum_query_integer}&", enum_query_integer=query.to_string())); + + + let uri = format!( + "{}/v2/fake?{enum_query_string_array}{enum_query_string}{enum_query_integer}", + self.base_path, + enum_query_string_array=utf8_percent_encode(&query_enum_query_string_array, QUERY_ENCODE_SET), + enum_query_string=utf8_percent_encode(&query_enum_query_string, QUERY_ENCODE_SET), + enum_query_integer=utf8_percent_encode(&query_enum_query_integer, QUERY_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Get, uri); + + let params = &[ + ("enum_form_string_array", param_enum_form_string_array.map(|param| format!("{:?}", param))), + ("enum_form_string", param_enum_form_string), + ("enum_query_double", param_enum_query_double.map(|param| format!("{:?}", param))), + ]; + let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize"); + + request.headers_mut().set(ContentType(mimetypes::requests::TEST_ENUM_PARAMETERS.clone())); + request.set_body(body.into_bytes()); + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + // Header parameters + header! { (RequestEnumHeaderStringArray, "enum_header_string_array") => (String)* } + param_enum_header_string_array.map(|header| request.headers_mut().set(RequestEnumHeaderStringArray(header.clone()))); + header! { (RequestEnumHeaderString, "enum_header_string") => [String] } + param_enum_header_string.map(|header| request.headers_mut().set(RequestEnumHeaderString(header))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 400 => { + let body = response.body(); + Box::new( + + future::ok( + TestEnumParametersResponse::InvalidRequest + ) + ) as Box> + }, + 404 => { + let body = response.body(); + Box::new( + + future::ok( + TestEnumParametersResponse::NotFound + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn test_inline_additional_properties(&self, param_param: object, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/fake/inline-additionalProperties", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + + let body = serde_json::to_string(¶m_param).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::TEST_INLINE_ADDITIONAL_PROPERTIES.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + future::ok( + TestInlineAdditionalPropertiesResponse::SuccessfulOperation + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn test_json_form_data(&self, param_param: String, param_param2: String, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/fake/jsonFormData", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Get, uri); + + let params = &[ + ("param", Some(param_param)), + ("param2", Some(param_param2)), + ]; + let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize"); + + request.headers_mut().set(ContentType(mimetypes::requests::TEST_JSON_FORM_DATA.clone())); + request.set_body(body.into_bytes()); + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + future::ok( + TestJsonFormDataResponse::SuccessfulOperation + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn test_classname(&self, param_body: models::Client, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/fake_classname_test", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Patch, uri); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::TEST_CLASSNAME.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + serde_json::from_str::(body) + .map_err(|e| e.into()) + + )) + .map(move |body| + TestClassnameResponse::SuccessfulOperation(body) + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn add_pet(&self, param_body: models::Pet, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/pet", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + + let body = serde_xml_rs::to_string(¶m_body).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::ADD_PET.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 405 => { + let body = response.body(); + Box::new( + + future::ok( + AddPetResponse::InvalidInput + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn delete_pet(&self, param_pet_id: i64, param_api_key: Option, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/pet/{petId}", + self.base_path, petId=utf8_percent_encode(¶m_pet_id.to_string(), PATH_SEGMENT_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Delete, uri); + + + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + // Header parameters + header! { (RequestApiKey, "api_key") => [String] } + param_api_key.map(|header| request.headers_mut().set(RequestApiKey(header))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 400 => { + let body = response.body(); + Box::new( + + future::ok( + DeletePetResponse::InvalidPetValue + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn find_pets_by_status(&self, param_status: &Vec, context: &Context) -> Box> { + + // Query parameters + let query_status = format!("status={status}&", status=param_status.join(",")); + + + let uri = format!( + "{}/v2/pet/findByStatus?{status}", + self.base_path, + status=utf8_percent_encode(&query_status, QUERY_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Get, uri); + + + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + serde_xml_rs::from_str::>(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e))) + + )) + .map(move |body| + FindPetsByStatusResponse::SuccessfulOperation(body) + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + FindPetsByStatusResponse::InvalidStatusValue + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn find_pets_by_tags(&self, param_tags: &Vec, context: &Context) -> Box> { + + // Query parameters + let query_tags = format!("tags={tags}&", tags=param_tags.join(",")); + + + let uri = format!( + "{}/v2/pet/findByTags?{tags}", + self.base_path, + tags=utf8_percent_encode(&query_tags, QUERY_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Get, uri); + + + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + serde_xml_rs::from_str::>(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e))) + + )) + .map(move |body| + FindPetsByTagsResponse::SuccessfulOperation(body) + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + FindPetsByTagsResponse::InvalidTagValue + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn get_pet_by_id(&self, param_pet_id: i64, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/pet/{petId}", + self.base_path, petId=utf8_percent_encode(¶m_pet_id.to_string(), PATH_SEGMENT_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Get, uri); + + + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + serde_xml_rs::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e))) + + )) + .map(move |body| + GetPetByIdResponse::SuccessfulOperation(body) + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + GetPetByIdResponse::InvalidIDSupplied + ) + ) as Box> + }, + 404 => { + let body = response.body(); + Box::new( + + future::ok( + GetPetByIdResponse::PetNotFound + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn update_pet(&self, param_body: models::Pet, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/pet", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Put, uri); + + + let body = serde_xml_rs::to_string(¶m_body).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::UPDATE_PET.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 400 => { + let body = response.body(); + Box::new( + + future::ok( + UpdatePetResponse::InvalidIDSupplied + ) + ) as Box> + }, + 404 => { + let body = response.body(); + Box::new( + + future::ok( + UpdatePetResponse::PetNotFound + ) + ) as Box> + }, + 405 => { + let body = response.body(); + Box::new( + + future::ok( + UpdatePetResponse::ValidationException + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn update_pet_with_form(&self, param_pet_id: i64, param_name: Option, param_status: Option, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/pet/{petId}", + self.base_path, petId=utf8_percent_encode(¶m_pet_id.to_string(), PATH_SEGMENT_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + let params = &[ + ("name", param_name), + ("status", param_status), + ]; + let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize"); + + request.headers_mut().set(ContentType(mimetypes::requests::UPDATE_PET_WITH_FORM.clone())); + request.set_body(body.into_bytes()); + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 405 => { + let body = response.body(); + Box::new( + + future::ok( + UpdatePetWithFormResponse::InvalidInput + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn upload_file(&self, param_pet_id: i64, param_additional_metadata: Option, param_file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/pet/{petId}/uploadImage", + self.base_path, petId=utf8_percent_encode(¶m_pet_id.to_string(), PATH_SEGMENT_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + // Form data body + let mut multipart = Multipart::new(); + + // Helper function to convert a Stream into a String. The String can then be used to build the HTTP body. + fn convert_stream_to_string(stream: Box, Error=Error> + Send>) -> Result { + + stream.concat2() + .wait() + .map_err(|e| ApiError(format!("Unable to collect stream: {}", e))) + .and_then(|body| String::from_utf8(body) + .map_err(|e| ApiError(format!("Failed to convert utf8 stream to String: {}", e)))) + } + + if let Ok(Some(param_file)) = param_file.wait() { + match convert_stream_to_string(param_file) { + Ok(param_file) => { + // Add file to multipart form. + multipart.add_text("file", param_file); + }, + Err(err) => return Box::new(futures::done(Err(err))), + } + } + + let mut fields = match multipart.prepare() { + Ok(fields) => fields, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build request: {}", err))))), + }; + + let mut body_string = String::new(); + let body = fields.to_body().read_to_string(&mut body_string); + let boundary = fields.boundary(); + let multipart_header = match mime::Mime::from_str(&format!("multipart/form-data;boundary={}", boundary)) { + Ok(multipart_header) => multipart_header, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build multipart header: {:?}", err))))), + }; + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + request.headers_mut().set(ContentType(multipart_header)); + request.set_body(body_string.into_bytes()); + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + serde_json::from_str::(body) + .map_err(|e| e.into()) + + )) + .map(move |body| + UploadFileResponse::SuccessfulOperation(body) + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn delete_order(&self, param_order_id: String, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/store/order/{order_id}", + self.base_path, order_id=utf8_percent_encode(¶m_order_id.to_string(), PATH_SEGMENT_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Delete, uri); + + + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 400 => { + let body = response.body(); + Box::new( + + future::ok( + DeleteOrderResponse::InvalidIDSupplied + ) + ) as Box> + }, + 404 => { + let body = response.body(); + Box::new( + + future::ok( + DeleteOrderResponse::OrderNotFound + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn get_inventory(&self, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/store/inventory", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Get, uri); + + + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + serde_json::from_str::>(body) + .map_err(|e| e.into()) + + )) + .map(move |body| + GetInventoryResponse::SuccessfulOperation(body) + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn get_order_by_id(&self, param_order_id: i64, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/store/order/{order_id}", + self.base_path, order_id=utf8_percent_encode(¶m_order_id.to_string(), PATH_SEGMENT_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Get, uri); + + + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + serde_xml_rs::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e))) + + )) + .map(move |body| + GetOrderByIdResponse::SuccessfulOperation(body) + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + GetOrderByIdResponse::InvalidIDSupplied + ) + ) as Box> + }, + 404 => { + let body = response.body(); + Box::new( + + future::ok( + GetOrderByIdResponse::OrderNotFound + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn place_order(&self, param_body: models::Order, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/store/order", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::PLACE_ORDER.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + serde_xml_rs::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e))) + + )) + .map(move |body| + PlaceOrderResponse::SuccessfulOperation(body) + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + PlaceOrderResponse::InvalidOrder + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn create_user(&self, param_body: models::User, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/user", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::CREATE_USER.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 0 => { + let body = response.body(); + Box::new( + + future::ok( + CreateUserResponse::SuccessfulOperation + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn create_users_with_array_input(&self, param_body: &Vec, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/user/createWithArray", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::CREATE_USERS_WITH_ARRAY_INPUT.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 0 => { + let body = response.body(); + Box::new( + + future::ok( + CreateUsersWithArrayInputResponse::SuccessfulOperation + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn create_users_with_list_input(&self, param_body: &Vec, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/user/createWithList", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::CREATE_USERS_WITH_LIST_INPUT.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 0 => { + let body = response.body(); + Box::new( + + future::ok( + CreateUsersWithListInputResponse::SuccessfulOperation + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn delete_user(&self, param_username: String, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/user/{username}", + self.base_path, username=utf8_percent_encode(¶m_username.to_string(), PATH_SEGMENT_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Delete, uri); + + + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 400 => { + let body = response.body(); + Box::new( + + future::ok( + DeleteUserResponse::InvalidUsernameSupplied + ) + ) as Box> + }, + 404 => { + let body = response.body(); + Box::new( + + future::ok( + DeleteUserResponse::UserNotFound + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn get_user_by_name(&self, param_username: String, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/user/{username}", + self.base_path, username=utf8_percent_encode(¶m_username.to_string(), PATH_SEGMENT_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Get, uri); + + + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + serde_xml_rs::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e))) + + )) + .map(move |body| + GetUserByNameResponse::SuccessfulOperation(body) + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + GetUserByNameResponse::InvalidUsernameSupplied + ) + ) as Box> + }, + 404 => { + let body = response.body(); + Box::new( + + future::ok( + GetUserByNameResponse::UserNotFound + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn login_user(&self, param_username: String, param_password: String, context: &Context) -> Box> { + + // Query parameters + let query_username = format!("username={username}&", username=param_username.to_string()); + let query_password = format!("password={password}&", password=param_password.to_string()); + + + let uri = format!( + "{}/v2/user/login?{username}{password}", + self.base_path, + username=utf8_percent_encode(&query_username, QUERY_ENCODE_SET), + password=utf8_percent_encode(&query_password, QUERY_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Get, uri); + + + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 200 => { + header! { (ResponseXRateLimit, "X-Rate-Limit") => [i32] } + let response_x_rate_limit = match response.headers().get::() { + Some(response_x_rate_limit) => response_x_rate_limit.0.clone(), + None => return Box::new(future::err(ApiError(String::from("Required response header X-Rate-Limit for response 200 was not found.")))) as Box>, + }; + header! { (ResponseXExpiresAfter, "X-Expires-After") => [chrono::DateTime] } + let response_x_expires_after = match response.headers().get::() { + Some(response_x_expires_after) => response_x_expires_after.0.clone(), + None => return Box::new(future::err(ApiError(String::from("Required response header X-Expires-After for response 200 was not found.")))) as Box>, + }; + let body = response.body(); + Box::new( + + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + serde_xml_rs::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e))) + + )) + .map(move |body| + LoginUserResponse::SuccessfulOperation{ body: body, x_rate_limit: response_x_rate_limit, x_expires_after: response_x_expires_after } + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + LoginUserResponse::InvalidUsername + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn logout_user(&self, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/user/logout", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Get, uri); + + + + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 0 => { + let body = response.body(); + Box::new( + + future::ok( + LogoutUserResponse::SuccessfulOperation + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn update_user(&self, param_username: String, param_body: models::User, context: &Context) -> Box> { + + + let uri = format!( + "{}/v2/user/{username}", + self.base_path, username=utf8_percent_encode(¶m_username.to_string(), PATH_SEGMENT_ENCODE_SET) + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Put, uri); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::UPDATE_USER.clone())); + context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + + + + + let hyper_client = (self.hyper_client)(&*self.handle); + Box::new(hyper_client.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 400 => { + let body = response.body(); + Box::new( + + future::ok( + UpdateUserResponse::InvalidUserSupplied + ) + ) as Box> + }, + 404 => { + let body = response.body(); + Box::new( + + future::ok( + UpdateUserResponse::UserNotFound + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + +} + +#[derive(Debug)] +pub enum ClientInitError { + InvalidScheme, + InvalidUri(hyper::error::UriError), + MissingHost, + SslError(openssl::error::ErrorStack) +} + +impl From for ClientInitError { + fn from(err: hyper::error::UriError) -> ClientInitError { + ClientInitError::InvalidUri(err) + } +} + +impl From for ClientInitError { + fn from(err: openssl::error::ErrorStack) -> ClientInitError { + ClientInitError::SslError(err) + } +} + +impl fmt::Display for ClientInitError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + (self as &fmt::Debug).fmt(f) + } +} + +impl error::Error for ClientInitError { + fn description(&self) -> &str { + "Failed to produce a hyper client." + } +} diff --git a/samples/server/petstore/rust-server/src/lib.rs b/samples/server/petstore/rust-server/src/lib.rs index d7b80c2f1d1e..cdfe30c6d018 100644 --- a/samples/server/petstore/rust-server/src/lib.rs +++ b/samples/server/petstore/rust-server/src/lib.rs @@ -3,10 +3,10 @@ extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; + extern crate serde_xml_rs; extern crate futures; extern crate chrono; -extern crate multipart; #[macro_use] extern crate lazy_static; #[macro_use] @@ -32,6 +32,9 @@ mod mimetypes; pub use swagger::{ApiError, Context, ContextWrapper}; +pub const BASE_PATH: &'static str = "/v2"; +pub const API_VERSION: &'static str = "1.0.0"; + #[derive(Debug, PartialEq)] pub enum TestSpecialTagsResponse { @@ -39,6 +42,12 @@ pub enum TestSpecialTagsResponse { SuccessfulOperation ( models::Client ) , } +#[derive(Debug, PartialEq)] +pub enum TestBodyWithQueryParamsResponse { + /// Success + Success , +} + #[derive(Debug, PartialEq)] pub enum FakeOuterBooleanSerializeResponse { /// Output boolean @@ -258,97 +267,100 @@ pub enum UpdateUserResponse { pub trait Api { /// To test special tags - fn test_special_tags(&self, body: models::Client, context: &Context) -> Box + Send>; + fn test_special_tags(&self, body: models::Client, context: &Context) -> Box>; + + fn test_body_with_query_params(&self, body: models::User, query: String, context: &Context) -> Box>; - fn fake_outer_boolean_serialize(&self, body: Option, context: &Context) -> Box + Send>; + fn fake_outer_boolean_serialize(&self, body: Option, context: &Context) -> Box>; - fn fake_outer_composite_serialize(&self, body: Option, context: &Context) -> Box + Send>; + fn fake_outer_composite_serialize(&self, body: Option, context: &Context) -> Box>; - fn fake_outer_number_serialize(&self, body: Option, context: &Context) -> Box + Send>; + fn fake_outer_number_serialize(&self, body: Option, context: &Context) -> Box>; - fn fake_outer_string_serialize(&self, body: Option, context: &Context) -> Box + Send>; + + fn fake_outer_string_serialize(&self, body: Option, context: &Context) -> Box>; /// To test \"client\" model - fn test_client_model(&self, body: models::Client, context: &Context) -> Box + Send>; + fn test_client_model(&self, body: models::Client, context: &Context) -> Box>; /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &Context) -> Box + Send>; + fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &Context) -> Box>; /// To test enum parameters - fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option, context: &Context) -> Box + Send>; + fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option, context: &Context) -> Box>; /// test inline additionalProperties - fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box + Send>; + fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box>; /// test json serialization of form data - fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box + Send>; + fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box>; /// To test class name in snake case - fn test_classname(&self, body: models::Client, context: &Context) -> Box + Send>; + fn test_classname(&self, body: models::Client, context: &Context) -> Box>; /// Add a new pet to the store - fn add_pet(&self, body: models::Pet, context: &Context) -> Box + Send>; + fn add_pet(&self, body: models::Pet, context: &Context) -> Box>; /// Deletes a pet - fn delete_pet(&self, pet_id: i64, api_key: Option, context: &Context) -> Box + Send>; + fn delete_pet(&self, pet_id: i64, api_key: Option, context: &Context) -> Box>; /// Finds Pets by status - fn find_pets_by_status(&self, status: &Vec, context: &Context) -> Box + Send>; + fn find_pets_by_status(&self, status: &Vec, context: &Context) -> Box>; /// Finds Pets by tags - fn find_pets_by_tags(&self, tags: &Vec, context: &Context) -> Box + Send>; + fn find_pets_by_tags(&self, tags: &Vec, context: &Context) -> Box>; /// Find pet by ID - fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box + Send>; + fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box>; /// Update an existing pet - fn update_pet(&self, body: models::Pet, context: &Context) -> Box + Send>; + fn update_pet(&self, body: models::Pet, context: &Context) -> Box>; /// Updates a pet in the store with form data - fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &Context) -> Box + Send>; + fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &Context) -> Box>; /// uploads an image - fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box + Send>; + fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box>; /// Delete purchase order by ID - fn delete_order(&self, order_id: String, context: &Context) -> Box + Send>; + fn delete_order(&self, order_id: String, context: &Context) -> Box>; /// Returns pet inventories by status - fn get_inventory(&self, context: &Context) -> Box + Send>; + fn get_inventory(&self, context: &Context) -> Box>; /// Find purchase order by ID - fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box + Send>; + fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box>; /// Place an order for a pet - fn place_order(&self, body: models::Order, context: &Context) -> Box + Send>; + fn place_order(&self, body: models::Order, context: &Context) -> Box>; /// Create user - fn create_user(&self, body: models::User, context: &Context) -> Box + Send>; + fn create_user(&self, body: models::User, context: &Context) -> Box>; /// Creates list of users with given input array - fn create_users_with_array_input(&self, body: &Vec, context: &Context) -> Box + Send>; + fn create_users_with_array_input(&self, body: &Vec, context: &Context) -> Box>; /// Creates list of users with given input array - fn create_users_with_list_input(&self, body: &Vec, context: &Context) -> Box + Send>; + fn create_users_with_list_input(&self, body: &Vec, context: &Context) -> Box>; /// Delete user - fn delete_user(&self, username: String, context: &Context) -> Box + Send>; + fn delete_user(&self, username: String, context: &Context) -> Box>; /// Get user by user name - fn get_user_by_name(&self, username: String, context: &Context) -> Box + Send>; + fn get_user_by_name(&self, username: String, context: &Context) -> Box>; /// Logs user into the system - fn login_user(&self, username: String, password: String, context: &Context) -> Box + Send>; + fn login_user(&self, username: String, password: String, context: &Context) -> Box>; /// Logs out current logged in user session - fn logout_user(&self, context: &Context) -> Box + Send>; + fn logout_user(&self, context: &Context) -> Box>; /// Updated user - fn update_user(&self, username: String, body: models::User, context: &Context) -> Box + Send>; + fn update_user(&self, username: String, body: models::User, context: &Context) -> Box>; } @@ -356,97 +368,100 @@ pub trait Api { pub trait ApiNoContext { /// To test special tags - fn test_special_tags(&self, body: models::Client) -> Box + Send>; + fn test_special_tags(&self, body: models::Client) -> Box>; + + + fn test_body_with_query_params(&self, body: models::User, query: String) -> Box>; - fn fake_outer_boolean_serialize(&self, body: Option) -> Box + Send>; + fn fake_outer_boolean_serialize(&self, body: Option) -> Box>; - fn fake_outer_composite_serialize(&self, body: Option) -> Box + Send>; + fn fake_outer_composite_serialize(&self, body: Option) -> Box>; - fn fake_outer_number_serialize(&self, body: Option) -> Box + Send>; + fn fake_outer_number_serialize(&self, body: Option) -> Box>; - fn fake_outer_string_serialize(&self, body: Option) -> Box + Send>; + fn fake_outer_string_serialize(&self, body: Option) -> Box>; /// To test \"client\" model - fn test_client_model(&self, body: models::Client) -> Box + Send>; + fn test_client_model(&self, body: models::Client) -> Box>; /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option) -> Box + Send>; + fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option) -> Box>; /// To test enum parameters - fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option) -> Box + Send>; + fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option) -> Box>; /// test inline additionalProperties - fn test_inline_additional_properties(&self, param: object) -> Box + Send>; + fn test_inline_additional_properties(&self, param: object) -> Box>; /// test json serialization of form data - fn test_json_form_data(&self, param: String, param2: String) -> Box + Send>; + fn test_json_form_data(&self, param: String, param2: String) -> Box>; /// To test class name in snake case - fn test_classname(&self, body: models::Client) -> Box + Send>; + fn test_classname(&self, body: models::Client) -> Box>; /// Add a new pet to the store - fn add_pet(&self, body: models::Pet) -> Box + Send>; + fn add_pet(&self, body: models::Pet) -> Box>; /// Deletes a pet - fn delete_pet(&self, pet_id: i64, api_key: Option) -> Box + Send>; + fn delete_pet(&self, pet_id: i64, api_key: Option) -> Box>; /// Finds Pets by status - fn find_pets_by_status(&self, status: &Vec) -> Box + Send>; + fn find_pets_by_status(&self, status: &Vec) -> Box>; /// Finds Pets by tags - fn find_pets_by_tags(&self, tags: &Vec) -> Box + Send>; + fn find_pets_by_tags(&self, tags: &Vec) -> Box>; /// Find pet by ID - fn get_pet_by_id(&self, pet_id: i64) -> Box + Send>; + fn get_pet_by_id(&self, pet_id: i64) -> Box>; /// Update an existing pet - fn update_pet(&self, body: models::Pet) -> Box + Send>; + fn update_pet(&self, body: models::Pet) -> Box>; /// Updates a pet in the store with form data - fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option) -> Box + Send>; + fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option) -> Box>; /// uploads an image - fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>) -> Box + Send>; + fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>) -> Box>; /// Delete purchase order by ID - fn delete_order(&self, order_id: String) -> Box + Send>; + fn delete_order(&self, order_id: String) -> Box>; /// Returns pet inventories by status - fn get_inventory(&self) -> Box + Send>; + fn get_inventory(&self) -> Box>; /// Find purchase order by ID - fn get_order_by_id(&self, order_id: i64) -> Box + Send>; + fn get_order_by_id(&self, order_id: i64) -> Box>; /// Place an order for a pet - fn place_order(&self, body: models::Order) -> Box + Send>; + fn place_order(&self, body: models::Order) -> Box>; /// Create user - fn create_user(&self, body: models::User) -> Box + Send>; + fn create_user(&self, body: models::User) -> Box>; /// Creates list of users with given input array - fn create_users_with_array_input(&self, body: &Vec) -> Box + Send>; + fn create_users_with_array_input(&self, body: &Vec) -> Box>; /// Creates list of users with given input array - fn create_users_with_list_input(&self, body: &Vec) -> Box + Send>; + fn create_users_with_list_input(&self, body: &Vec) -> Box>; /// Delete user - fn delete_user(&self, username: String) -> Box + Send>; + fn delete_user(&self, username: String) -> Box>; /// Get user by user name - fn get_user_by_name(&self, username: String) -> Box + Send>; + fn get_user_by_name(&self, username: String) -> Box>; /// Logs user into the system - fn login_user(&self, username: String, password: String) -> Box + Send>; + fn login_user(&self, username: String, password: String) -> Box>; /// Logs out current logged in user session - fn logout_user(&self) -> Box + Send>; + fn logout_user(&self) -> Box>; /// Updated user - fn update_user(&self, username: String, body: models::User) -> Box + Send>; + fn update_user(&self, username: String, body: models::User) -> Box>; } @@ -465,157 +480,162 @@ impl<'a, T: Api + Sized> ContextWrapperExt<'a> for T { impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> { /// To test special tags - fn test_special_tags(&self, body: models::Client) -> Box + Send> { + fn test_special_tags(&self, body: models::Client) -> Box> { self.api().test_special_tags(body, &self.context()) } - fn fake_outer_boolean_serialize(&self, body: Option) -> Box + Send> { + fn test_body_with_query_params(&self, body: models::User, query: String) -> Box> { + self.api().test_body_with_query_params(body, query, &self.context()) + } + + + fn fake_outer_boolean_serialize(&self, body: Option) -> Box> { self.api().fake_outer_boolean_serialize(body, &self.context()) } - fn fake_outer_composite_serialize(&self, body: Option) -> Box + Send> { + fn fake_outer_composite_serialize(&self, body: Option) -> Box> { self.api().fake_outer_composite_serialize(body, &self.context()) } - fn fake_outer_number_serialize(&self, body: Option) -> Box + Send> { + fn fake_outer_number_serialize(&self, body: Option) -> Box> { self.api().fake_outer_number_serialize(body, &self.context()) } - fn fake_outer_string_serialize(&self, body: Option) -> Box + Send> { + fn fake_outer_string_serialize(&self, body: Option) -> Box> { self.api().fake_outer_string_serialize(body, &self.context()) } /// To test \"client\" model - fn test_client_model(&self, body: models::Client) -> Box + Send> { + fn test_client_model(&self, body: models::Client) -> Box> { self.api().test_client_model(body, &self.context()) } /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option) -> Box + Send> { + fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option) -> Box> { self.api().test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, &self.context()) } /// To test enum parameters - fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option) -> Box + Send> { + fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option) -> Box> { self.api().test_enum_parameters(enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, &self.context()) } /// test inline additionalProperties - fn test_inline_additional_properties(&self, param: object) -> Box + Send> { + fn test_inline_additional_properties(&self, param: object) -> Box> { self.api().test_inline_additional_properties(param, &self.context()) } /// test json serialization of form data - fn test_json_form_data(&self, param: String, param2: String) -> Box + Send> { + fn test_json_form_data(&self, param: String, param2: String) -> Box> { self.api().test_json_form_data(param, param2, &self.context()) } /// To test class name in snake case - fn test_classname(&self, body: models::Client) -> Box + Send> { + fn test_classname(&self, body: models::Client) -> Box> { self.api().test_classname(body, &self.context()) } /// Add a new pet to the store - fn add_pet(&self, body: models::Pet) -> Box + Send> { + fn add_pet(&self, body: models::Pet) -> Box> { self.api().add_pet(body, &self.context()) } /// Deletes a pet - fn delete_pet(&self, pet_id: i64, api_key: Option) -> Box + Send> { + fn delete_pet(&self, pet_id: i64, api_key: Option) -> Box> { self.api().delete_pet(pet_id, api_key, &self.context()) } /// Finds Pets by status - fn find_pets_by_status(&self, status: &Vec) -> Box + Send> { + fn find_pets_by_status(&self, status: &Vec) -> Box> { self.api().find_pets_by_status(status, &self.context()) } /// Finds Pets by tags - fn find_pets_by_tags(&self, tags: &Vec) -> Box + Send> { + fn find_pets_by_tags(&self, tags: &Vec) -> Box> { self.api().find_pets_by_tags(tags, &self.context()) } /// Find pet by ID - fn get_pet_by_id(&self, pet_id: i64) -> Box + Send> { + fn get_pet_by_id(&self, pet_id: i64) -> Box> { self.api().get_pet_by_id(pet_id, &self.context()) } /// Update an existing pet - fn update_pet(&self, body: models::Pet) -> Box + Send> { + fn update_pet(&self, body: models::Pet) -> Box> { self.api().update_pet(body, &self.context()) } /// Updates a pet in the store with form data - fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option) -> Box + Send> { + fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option) -> Box> { self.api().update_pet_with_form(pet_id, name, status, &self.context()) } /// uploads an image - fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>) -> Box + Send> { + fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>) -> Box> { self.api().upload_file(pet_id, additional_metadata, file, &self.context()) } /// Delete purchase order by ID - fn delete_order(&self, order_id: String) -> Box + Send> { + fn delete_order(&self, order_id: String) -> Box> { self.api().delete_order(order_id, &self.context()) } /// Returns pet inventories by status - fn get_inventory(&self) -> Box + Send> { + fn get_inventory(&self) -> Box> { self.api().get_inventory(&self.context()) } /// Find purchase order by ID - fn get_order_by_id(&self, order_id: i64) -> Box + Send> { + fn get_order_by_id(&self, order_id: i64) -> Box> { self.api().get_order_by_id(order_id, &self.context()) } /// Place an order for a pet - fn place_order(&self, body: models::Order) -> Box + Send> { + fn place_order(&self, body: models::Order) -> Box> { self.api().place_order(body, &self.context()) } /// Create user - fn create_user(&self, body: models::User) -> Box + Send> { + fn create_user(&self, body: models::User) -> Box> { self.api().create_user(body, &self.context()) } /// Creates list of users with given input array - fn create_users_with_array_input(&self, body: &Vec) -> Box + Send> { + fn create_users_with_array_input(&self, body: &Vec) -> Box> { self.api().create_users_with_array_input(body, &self.context()) } /// Creates list of users with given input array - fn create_users_with_list_input(&self, body: &Vec) -> Box + Send> { + fn create_users_with_list_input(&self, body: &Vec) -> Box> { self.api().create_users_with_list_input(body, &self.context()) } /// Delete user - fn delete_user(&self, username: String) -> Box + Send> { + fn delete_user(&self, username: String) -> Box> { self.api().delete_user(username, &self.context()) } /// Get user by user name - fn get_user_by_name(&self, username: String) -> Box + Send> { + fn get_user_by_name(&self, username: String) -> Box> { self.api().get_user_by_name(username, &self.context()) } /// Logs user into the system - fn login_user(&self, username: String, password: String) -> Box + Send> { + fn login_user(&self, username: String, password: String) -> Box> { self.api().login_user(username, password, &self.context()) } /// Logs out current logged in user session - fn logout_user(&self) -> Box + Send> { + fn logout_user(&self) -> Box> { self.api().logout_user(&self.context()) } /// Updated user - fn update_user(&self, username: String, body: models::User) -> Box + Send> { + fn update_user(&self, username: String, body: models::User) -> Box> { self.api().update_user(username, body, &self.context()) } @@ -633,6 +653,6 @@ pub mod server; // Re-export router() as a top-level name #[cfg(feature = "server")] -pub use self::server::router; +pub use self::server::Service; pub mod models; diff --git a/samples/server/petstore/rust-server/src/mimetypes.rs b/samples/server/petstore/rust-server/src/mimetypes.rs index c35afc74ff37..1ad0e1d9b0c3 100644 --- a/samples/server/petstore/rust-server/src/mimetypes.rs +++ b/samples/server/petstore/rust-server/src/mimetypes.rs @@ -61,30 +61,46 @@ pub mod requests { lazy_static! { pub static ref TEST_SPECIAL_TAGS: Mime = "application/json".parse().unwrap(); } + /// Create Mime objects for the request content types for TestBodyWithQueryParams + lazy_static! { + pub static ref TEST_BODY_WITH_QUERY_PARAMS: Mime = "application/json".parse().unwrap(); + } /// Create Mime objects for the request content types for FakeOuterBooleanSerialize lazy_static! { - pub static ref FAKE_OUTER_BOOLEAN_SERIALIZE: Mime = "Application/Json".parse().unwrap(); + pub static ref FAKE_OUTER_BOOLEAN_SERIALIZE: Mime = "application/json".parse().unwrap(); } /// Create Mime objects for the request content types for FakeOuterCompositeSerialize lazy_static! { - pub static ref FAKE_OUTER_COMPOSITE_SERIALIZE: Mime = "Application/Json".parse().unwrap(); + pub static ref FAKE_OUTER_COMPOSITE_SERIALIZE: Mime = "application/json".parse().unwrap(); } /// Create Mime objects for the request content types for FakeOuterNumberSerialize lazy_static! { - pub static ref FAKE_OUTER_NUMBER_SERIALIZE: Mime = "Application/Json".parse().unwrap(); + pub static ref FAKE_OUTER_NUMBER_SERIALIZE: Mime = "application/json".parse().unwrap(); } /// Create Mime objects for the request content types for FakeOuterStringSerialize lazy_static! { - pub static ref FAKE_OUTER_STRING_SERIALIZE: Mime = "Application/Json".parse().unwrap(); + pub static ref FAKE_OUTER_STRING_SERIALIZE: Mime = "application/json".parse().unwrap(); } /// Create Mime objects for the request content types for TestClientModel lazy_static! { pub static ref TEST_CLIENT_MODEL: Mime = "application/json".parse().unwrap(); } + /// Create Mime objects for the request content types for TestEndpointParameters + lazy_static! { + pub static ref TEST_ENDPOINT_PARAMETERS: Mime = "application/xml; charset=utf-8".parse().unwrap(); + } + /// Create Mime objects for the request content types for TestEnumParameters + lazy_static! { + pub static ref TEST_ENUM_PARAMETERS: Mime = "*/*".parse().unwrap(); + } /// Create Mime objects for the request content types for TestInlineAdditionalProperties lazy_static! { pub static ref TEST_INLINE_ADDITIONAL_PROPERTIES: Mime = "application/json".parse().unwrap(); } + /// Create Mime objects for the request content types for TestJsonFormData + lazy_static! { + pub static ref TEST_JSON_FORM_DATA: Mime = "application/json".parse().unwrap(); + } /// Create Mime objects for the request content types for TestClassname lazy_static! { pub static ref TEST_CLASSNAME: Mime = "application/json".parse().unwrap(); @@ -97,25 +113,29 @@ pub mod requests { lazy_static! { pub static ref UPDATE_PET: Mime = "application/json".parse().unwrap(); } + /// Create Mime objects for the request content types for UpdatePetWithForm + lazy_static! { + pub static ref UPDATE_PET_WITH_FORM: Mime = "application/x-www-form-urlencoded".parse().unwrap(); + } /// Create Mime objects for the request content types for PlaceOrder lazy_static! { - pub static ref PLACE_ORDER: Mime = "Application/Json".parse().unwrap(); + pub static ref PLACE_ORDER: Mime = "application/json".parse().unwrap(); } /// Create Mime objects for the request content types for CreateUser lazy_static! { - pub static ref CREATE_USER: Mime = "Application/Json".parse().unwrap(); + pub static ref CREATE_USER: Mime = "application/json".parse().unwrap(); } /// Create Mime objects for the request content types for CreateUsersWithArrayInput lazy_static! { - pub static ref CREATE_USERS_WITH_ARRAY_INPUT: Mime = "Application/Json".parse().unwrap(); + pub static ref CREATE_USERS_WITH_ARRAY_INPUT: Mime = "application/json".parse().unwrap(); } /// Create Mime objects for the request content types for CreateUsersWithListInput lazy_static! { - pub static ref CREATE_USERS_WITH_LIST_INPUT: Mime = "Application/Json".parse().unwrap(); + pub static ref CREATE_USERS_WITH_LIST_INPUT: Mime = "application/json".parse().unwrap(); } /// Create Mime objects for the request content types for UpdateUser lazy_static! { - pub static ref UPDATE_USER: Mime = "Application/Json".parse().unwrap(); + pub static ref UPDATE_USER: Mime = "application/json".parse().unwrap(); } } diff --git a/samples/server/petstore/rust-server/src/models.rs b/samples/server/petstore/rust-server/src/models.rs index e674239da35c..ce98abe8dca1 100644 --- a/samples/server/petstore/rust-server/src/models.rs +++ b/samples/server/petstore/rust-server/src/models.rs @@ -361,6 +361,10 @@ pub struct EnumTest { #[serde(skip_serializing_if="Option::is_none")] pub enum_string: Option, + // Note: inline enums are not fully supported by swagger-codegen + #[serde(rename = "enum_string_required")] + pub enum_string_required: String, + // Note: inline enums are not fully supported by swagger-codegen #[serde(rename = "enum_integer")] #[serde(skip_serializing_if="Option::is_none")] @@ -378,9 +382,10 @@ pub struct EnumTest { } impl EnumTest { - pub fn new() -> EnumTest { + pub fn new(enum_string_required: String, ) -> EnumTest { EnumTest { enum_string: None, + enum_string_required: enum_string_required, enum_integer: None, enum_number: None, outer_enum: None, diff --git a/samples/server/petstore/rust-server/src/server.rs b/samples/server/petstore/rust-server/src/server.rs deleted file mode 100644 index 675dae8ef561..000000000000 --- a/samples/server/petstore/rust-server/src/server.rs +++ /dev/null @@ -1,2481 +0,0 @@ -#![allow(unused_extern_crates)] -extern crate serde_ignored; -extern crate iron; -extern crate router; -extern crate bodyparser; -extern crate urlencoded; -extern crate uuid; -extern crate chrono; -extern crate multipart; - -use futures::Future; -use futures::future; -use futures::{stream, Stream}; -use hyper; -use hyper::header::{Headers, ContentType}; -use self::iron::prelude::*; -use self::iron::{status, modifiers, BeforeMiddleware}; -use self::iron::url::percent_encoding::percent_decode; -use self::router::Router; -use self::urlencoded::UrlEncodedQuery; -use mimetypes; -use multipart::server::{Multipart, SaveResult}; - -use serde_json; -use serde_xml_rs; - -#[allow(unused_imports)] -use std::collections::{HashMap, BTreeMap}; -#[allow(unused_imports)] -use swagger; -use std::io::Error; - -#[allow(unused_imports)] -use std::collections::BTreeSet; - -pub use swagger::auth::Authorization; -use swagger::auth::{AuthData, Scopes}; -use swagger::{ApiError, Context, XSpanId}; - -use {Api, - TestSpecialTagsResponse, - FakeOuterBooleanSerializeResponse, - FakeOuterCompositeSerializeResponse, - FakeOuterNumberSerializeResponse, - FakeOuterStringSerializeResponse, - TestClientModelResponse, - TestEndpointParametersResponse, - TestEnumParametersResponse, - TestInlineAdditionalPropertiesResponse, - TestJsonFormDataResponse, - TestClassnameResponse, - AddPetResponse, - DeletePetResponse, - FindPetsByStatusResponse, - FindPetsByTagsResponse, - GetPetByIdResponse, - UpdatePetResponse, - UpdatePetWithFormResponse, - UploadFileResponse, - DeleteOrderResponse, - GetInventoryResponse, - GetOrderByIdResponse, - PlaceOrderResponse, - CreateUserResponse, - CreateUsersWithArrayInputResponse, - CreateUsersWithListInputResponse, - DeleteUserResponse, - GetUserByNameResponse, - LoginUserResponse, - LogoutUserResponse, - UpdateUserResponse - }; -#[allow(unused_imports)] -use models; - -header! { (Warning, "Warning") => [String] } - -/// Create a new router for `Api` -pub fn router(api: T) -> Router where T: Api + Send + Sync + Clone + 'static { - let mut router = Router::new(); - add_routes(&mut router, api); - router -} - -/// Add routes for `Api` to a provided router. -/// -/// Note that these routes are added straight onto the router. This means that if the router -/// already has a route for an endpoint which clashes with those provided by this API, then the -/// old route will be lost. -/// -/// It is generally a bad idea to add routes in this way to an existing router, which may have -/// routes on it for other APIs. Distinct APIs should be behind distinct paths to encourage -/// separation of interfaces, which this function does not enforce. APIs should not overlap. -/// -/// Alternative approaches include: -/// -/// - generate an `iron::middleware::Handler` (usually a `router::Router` or -/// `iron::middleware::chain`) for each interface, and add those handlers inside an existing -/// router, mounted at different paths - so the interfaces are separated by path -/// - use a different instance of `iron::Iron` for each interface - so the interfaces are -/// separated by the address/port they listen on -/// -/// This function exists to allow legacy code, which doesn't separate its APIs properly, to make -/// use of this crate. -#[deprecated(note="APIs should not overlap - only for use in legacy code.")] -pub fn route(router: &mut Router, api: T) where T: Api + Send + Sync + Clone + 'static { - add_routes(router, api) -} - -/// Add routes for `Api` to a provided router -fn add_routes(router: &mut Router, api: T) where T: Api + Send + Sync + Clone + 'static { - - let api_clone = api.clone(); - router.patch( - "/v2/another-fake/dummy", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; - - param_body - } else { - None - }; - let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; - - - match api.test_special_tags(param_body, context).wait() { - Ok(rsp) => match rsp { - TestSpecialTagsResponse::SuccessfulOperation(body) => { - - let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - response.headers.set(ContentType(mimetypes::responses::TEST_SPECIAL_TAGS_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "TestSpecialTags"); - - let api_clone = api.clone(); - router.post( - "/v2/fake/outer/boolean", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().unwrap_or(None); - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).unwrap_or(None); - - param_body - } else { - None - };; - - - match api.fake_outer_boolean_serialize(param_body, context).wait() { - Ok(rsp) => match rsp { - FakeOuterBooleanSerializeResponse::OutputBoolean(body) => { - - let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "FakeOuterBooleanSerialize"); - - let api_clone = api.clone(); - router.post( - "/v2/fake/outer/composite", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().unwrap_or(None); - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).unwrap_or(None); - - param_body - } else { - None - };; - - - match api.fake_outer_composite_serialize(param_body, context).wait() { - Ok(rsp) => match rsp { - FakeOuterCompositeSerializeResponse::OutputComposite(body) => { - - let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "FakeOuterCompositeSerialize"); - - let api_clone = api.clone(); - router.post( - "/v2/fake/outer/number", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().unwrap_or(None); - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).unwrap_or(None); - - param_body - } else { - None - };; - - - match api.fake_outer_number_serialize(param_body, context).wait() { - Ok(rsp) => match rsp { - FakeOuterNumberSerializeResponse::OutputNumber(body) => { - - let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "FakeOuterNumberSerialize"); - - let api_clone = api.clone(); - router.post( - "/v2/fake/outer/string", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().unwrap_or(None); - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).unwrap_or(None); - - param_body - } else { - None - };; - - - match api.fake_outer_string_serialize(param_body, context).wait() { - Ok(rsp) => match rsp { - FakeOuterStringSerializeResponse::OutputString(body) => { - - let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "FakeOuterStringSerialize"); - - let api_clone = api.clone(); - router.patch( - "/v2/fake", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; - - param_body - } else { - None - }; - let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; - - - match api.test_client_model(param_body, context).wait() { - Ok(rsp) => match rsp { - TestClientModelResponse::SuccessfulOperation(body) => { - - let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - response.headers.set(ContentType(mimetypes::responses::TEST_CLIENT_MODEL_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "TestClientModel"); - - let api_clone = api.clone(); - router.post( - "/v2/fake", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - - - - // Form parameters - let param_number = 8.14; - let param_double = 1.2; - let param_pattern_without_delimiter = "pattern_without_delimiter_example".to_string(); - let param_byte = swagger::ByteArray(Vec::from("B")); - let param_integer = Some(56); - let param_int32 = Some(56); - let param_int64 = Some(789); - let param_float = Some(3.4); - let param_string = Some("string_example".to_string()); - let param_binary = Some(swagger::ByteArray(Vec::from("B"))); - let param_date = None; - let param_date_time = None; - let param_password = Some("password_example".to_string()); - let param_callback = Some("callback_example".to_string()); - - match api.test_endpoint_parameters(param_number, param_double, param_pattern_without_delimiter, param_byte, param_integer, param_int32, param_int64, param_float, param_string, param_binary, param_date, param_date_time, param_password, param_callback, context).wait() { - Ok(rsp) => match rsp { - TestEndpointParametersResponse::InvalidUsernameSupplied => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - TestEndpointParametersResponse::UserNotFound => { - - - let mut response = Response::with((status::Status::from_u16(404))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "TestEndpointParameters"); - - let api_clone = api.clone(); - router.get( - "/v2/fake", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - // Header parameters - header! { (RequestEnumHeaderStringArray, "enum_header_string_array") => (String)* } - let param_enum_header_string_array = req.headers.get::().map(|header| header.0.clone()); - header! { (RequestEnumHeaderString, "enum_header_string") => [String] } - let param_enum_header_string = req.headers.get::().map(|header| header.0.clone()); - - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = req.get::().unwrap_or_default(); - let param_enum_query_string_array = query_params.get("enum_query_string_array") - .map(|list| list.iter().flat_map(|x| x.parse::()).collect::>()); - let param_enum_query_string = query_params.get("enum_query_string") - .and_then(|list| list.first()).and_then(|x| x.parse::().ok()); - let param_enum_query_integer = query_params.get("enum_query_integer") - .and_then(|list| list.first()).and_then(|x| x.parse::().ok()); - - // Form parameters - let param_enum_form_string_array = None; - let param_enum_form_string = Some("enum_form_string_example".to_string()); - let param_enum_query_double = Some(1.2); - - match api.test_enum_parameters(param_enum_form_string_array.as_ref(), param_enum_form_string, param_enum_header_string_array.as_ref(), param_enum_header_string, param_enum_query_string_array.as_ref(), param_enum_query_string, param_enum_query_integer, param_enum_query_double, context).wait() { - Ok(rsp) => match rsp { - TestEnumParametersResponse::InvalidRequest => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - TestEnumParametersResponse::NotFound => { - - - let mut response = Response::with((status::Status::from_u16(404))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "TestEnumParameters"); - - let api_clone = api.clone(); - router.post( - "/v2/fake/inline-additionalProperties", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_param = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter param - not valid UTF-8: {}", e))))?; - - let mut unused_elements = Vec::new(); - - let param_param = if let Some(param_param_raw) = param_param { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_param_raw); - - let param_param: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter param - doesn't match schema: {}", e))))?; - - param_param - } else { - None - }; - let param_param = param_param.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter param".to_string())))?; - - - match api.test_inline_additional_properties(param_param, context).wait() { - Ok(rsp) => match rsp { - TestInlineAdditionalPropertiesResponse::SuccessfulOperation => { - - - let mut response = Response::with((status::Status::from_u16(200))); - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "TestInlineAdditionalProperties"); - - let api_clone = api.clone(); - router.get( - "/v2/fake/jsonFormData", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Form parameters - let param_param = "param_example".to_string(); - let param_param2 = "param2_example".to_string(); - - match api.test_json_form_data(param_param, param_param2, context).wait() { - Ok(rsp) => match rsp { - TestJsonFormDataResponse::SuccessfulOperation => { - - - let mut response = Response::with((status::Status::from_u16(200))); - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "TestJsonFormData"); - - let api_clone = api.clone(); - router.patch( - "/v2/fake_classname_test", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; - - param_body - } else { - None - }; - let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; - - - match api.test_classname(param_body, context).wait() { - Ok(rsp) => match rsp { - TestClassnameResponse::SuccessfulOperation(body) => { - - let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - response.headers.set(ContentType(mimetypes::responses::TEST_CLASSNAME_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "TestClassname"); - - let api_clone = api.clone(); - router.post( - "/v2/pet", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - // Authorization - if let Scopes::Some(ref scopes) = authorization.scopes { - let required_scopes: BTreeSet = vec![ - "write:pets".to_string(), // modify pets in your account - "read:pets".to_string(), // read your pets - ].into_iter().collect(); - - if !required_scopes.is_subset(scopes) { - let missing_scopes = required_scopes.difference(scopes); - return Err(Response::with(( - status::Forbidden, - missing_scopes.fold( - "Insufficient authorization, missing scopes".to_string(), - |s, scope| format!("{} {}", s, scope) - ) - ))); - } - } - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(param_body_raw.as_bytes()); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; - - param_body - } else { - None - }; - let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; - - - match api.add_pet(param_body, context).wait() { - Ok(rsp) => match rsp { - AddPetResponse::InvalidInput => { - - - let mut response = Response::with((status::Status::from_u16(405))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "AddPet"); - - let api_clone = api.clone(); - router.delete( - "/v2/pet/:petId", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - // Authorization - if let Scopes::Some(ref scopes) = authorization.scopes { - let required_scopes: BTreeSet = vec![ - "write:pets".to_string(), // modify pets in your account - "read:pets".to_string(), // read your pets - ].into_iter().collect(); - - if !required_scopes.is_subset(scopes) { - let missing_scopes = required_scopes.difference(scopes); - return Err(Response::with(( - status::Forbidden, - missing_scopes.fold( - "Insufficient authorization, missing scopes".to_string(), - |s, scope| format!("{} {}", s, scope) - ) - ))); - } - } - - - // Path parameters - let param_pet_id = { - let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? - .find("petId").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter petId".to_string())))?; - percent_decode(param.as_bytes()).decode_utf8() - .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? - .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter petId: {}", e))))? - }; - - // Header parameters - header! { (RequestApiKey, "api_key") => [String] } - let param_api_key = req.headers.get::().map(|header| header.0.clone()); - - - - match api.delete_pet(param_pet_id, param_api_key, context).wait() { - Ok(rsp) => match rsp { - DeletePetResponse::InvalidPetValue => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "DeletePet"); - - let api_clone = api.clone(); - router.get( - "/v2/pet/findByStatus", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - // Authorization - if let Scopes::Some(ref scopes) = authorization.scopes { - let required_scopes: BTreeSet = vec![ - "write:pets".to_string(), // modify pets in your account - "read:pets".to_string(), // read your pets - ].into_iter().collect(); - - if !required_scopes.is_subset(scopes) { - let missing_scopes = required_scopes.difference(scopes); - return Err(Response::with(( - status::Forbidden, - missing_scopes.fold( - "Insufficient authorization, missing scopes".to_string(), - |s, scope| format!("{} {}", s, scope) - ) - ))); - } - } - - - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = req.get::().unwrap_or_default(); - let param_status = query_params.get("status") - .ok_or_else(|| Response::with((status::BadRequest, "Missing required query parameter status".to_string())))? - .iter().flat_map(|x| x.parse::()).collect::>(); - - - match api.find_pets_by_status(param_status.as_ref(), context).wait() { - Ok(rsp) => match rsp { - FindPetsByStatusResponse::SuccessfulOperation(body) => { - - let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - response.headers.set(ContentType(mimetypes::responses::FIND_PETS_BY_STATUS_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - FindPetsByStatusResponse::InvalidStatusValue => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "FindPetsByStatus"); - - let api_clone = api.clone(); - router.get( - "/v2/pet/findByTags", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - // Authorization - if let Scopes::Some(ref scopes) = authorization.scopes { - let required_scopes: BTreeSet = vec![ - "write:pets".to_string(), // modify pets in your account - "read:pets".to_string(), // read your pets - ].into_iter().collect(); - - if !required_scopes.is_subset(scopes) { - let missing_scopes = required_scopes.difference(scopes); - return Err(Response::with(( - status::Forbidden, - missing_scopes.fold( - "Insufficient authorization, missing scopes".to_string(), - |s, scope| format!("{} {}", s, scope) - ) - ))); - } - } - - - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = req.get::().unwrap_or_default(); - let param_tags = query_params.get("tags") - .ok_or_else(|| Response::with((status::BadRequest, "Missing required query parameter tags".to_string())))? - .iter().flat_map(|x| x.parse::()).collect::>(); - - - match api.find_pets_by_tags(param_tags.as_ref(), context).wait() { - Ok(rsp) => match rsp { - FindPetsByTagsResponse::SuccessfulOperation(body) => { - - let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - response.headers.set(ContentType(mimetypes::responses::FIND_PETS_BY_TAGS_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - FindPetsByTagsResponse::InvalidTagValue => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "FindPetsByTags"); - - let api_clone = api.clone(); - router.get( - "/v2/pet/:petId", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - - - // Path parameters - let param_pet_id = { - let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? - .find("petId").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter petId".to_string())))?; - percent_decode(param.as_bytes()).decode_utf8() - .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? - .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter petId: {}", e))))? - }; - - - - match api.get_pet_by_id(param_pet_id, context).wait() { - Ok(rsp) => match rsp { - GetPetByIdResponse::SuccessfulOperation(body) => { - - let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - response.headers.set(ContentType(mimetypes::responses::GET_PET_BY_ID_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - GetPetByIdResponse::InvalidIDSupplied => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - GetPetByIdResponse::PetNotFound => { - - - let mut response = Response::with((status::Status::from_u16(404))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "GetPetById"); - - let api_clone = api.clone(); - router.put( - "/v2/pet", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - // Authorization - if let Scopes::Some(ref scopes) = authorization.scopes { - let required_scopes: BTreeSet = vec![ - "write:pets".to_string(), // modify pets in your account - "read:pets".to_string(), // read your pets - ].into_iter().collect(); - - if !required_scopes.is_subset(scopes) { - let missing_scopes = required_scopes.difference(scopes); - return Err(Response::with(( - status::Forbidden, - missing_scopes.fold( - "Insufficient authorization, missing scopes".to_string(), - |s, scope| format!("{} {}", s, scope) - ) - ))); - } - } - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(param_body_raw.as_bytes()); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; - - param_body - } else { - None - }; - let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; - - - match api.update_pet(param_body, context).wait() { - Ok(rsp) => match rsp { - UpdatePetResponse::InvalidIDSupplied => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - UpdatePetResponse::PetNotFound => { - - - let mut response = Response::with((status::Status::from_u16(404))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - UpdatePetResponse::ValidationException => { - - - let mut response = Response::with((status::Status::from_u16(405))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "UpdatePet"); - - let api_clone = api.clone(); - router.post( - "/v2/pet/:petId", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - // Authorization - if let Scopes::Some(ref scopes) = authorization.scopes { - let required_scopes: BTreeSet = vec![ - "write:pets".to_string(), // modify pets in your account - "read:pets".to_string(), // read your pets - ].into_iter().collect(); - - if !required_scopes.is_subset(scopes) { - let missing_scopes = required_scopes.difference(scopes); - return Err(Response::with(( - status::Forbidden, - missing_scopes.fold( - "Insufficient authorization, missing scopes".to_string(), - |s, scope| format!("{} {}", s, scope) - ) - ))); - } - } - - - // Path parameters - let param_pet_id = { - let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? - .find("petId").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter petId".to_string())))?; - percent_decode(param.as_bytes()).decode_utf8() - .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? - .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter petId: {}", e))))? - }; - - - // Form parameters - let param_name = Some("name_example".to_string()); - let param_status = Some("status_example".to_string()); - - match api.update_pet_with_form(param_pet_id, param_name, param_status, context).wait() { - Ok(rsp) => match rsp { - UpdatePetWithFormResponse::InvalidInput => { - - - let mut response = Response::with((status::Status::from_u16(405))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "UpdatePetWithForm"); - - let api_clone = api.clone(); - router.post( - "/v2/pet/:petId/uploadImage", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - // Authorization - if let Scopes::Some(ref scopes) = authorization.scopes { - let required_scopes: BTreeSet = vec![ - "write:pets".to_string(), // modify pets in your account - "read:pets".to_string(), // read your pets - ].into_iter().collect(); - - if !required_scopes.is_subset(scopes) { - let missing_scopes = required_scopes.difference(scopes); - return Err(Response::with(( - status::Forbidden, - missing_scopes.fold( - "Insufficient authorization, missing scopes".to_string(), - |s, scope| format!("{} {}", s, scope) - ) - ))); - } - } - - - // Path parameters - let param_pet_id = { - let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? - .find("petId").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter petId".to_string())))?; - percent_decode(param.as_bytes()).decode_utf8() - .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? - .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter petId: {}", e))))? - }; - - - // Form parameters - - // Expecting a multipart form, extract and parse it now. - let mut entries = match Multipart::from_request(req) { - Ok(mut multipart) => { - - match multipart.save().temp() { - SaveResult::Full(entries) => { - Ok(entries) - }, - _ => { - Err(Response::with((status::InternalServerError, format!("Unable to process all message parts")))) - }, - } - }, - Err(e) => { - // Unable to parse as multipart - Err(Response::with((status::BadRequest, format!("Couldn't parse body as multipart")))) - } - }?; - - let param_additional_metadata = Some("additional_metadata_example".to_string()); - - - let param_file = entries.fields.remove("file"); - - let param_file = match param_file { - Some(body) => { - Ok({let bytes = body.as_bytes(); - Some( - Box::new(stream::once(Ok(bytes.to_vec()))) as Box, Error=Error> + Send> - )} - ) - } - None => {Err(Response::with((status::BadRequest, format!("Body part not found!"))))} - }?; - let param_file = Box::new(future::ok(param_file)); - - match api.upload_file(param_pet_id, param_additional_metadata, param_file, context).wait() { - Ok(rsp) => match rsp { - UploadFileResponse::SuccessfulOperation(body) => { - - let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - response.headers.set(ContentType(mimetypes::responses::UPLOAD_FILE_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "UploadFile"); - - let api_clone = api.clone(); - router.delete( - "/v2/store/order/:order_id", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - // Path parameters - let param_order_id = { - let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? - .find("order_id").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter order_id".to_string())))?; - percent_decode(param.as_bytes()).decode_utf8() - .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? - .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter order_id: {}", e))))? - }; - - - - match api.delete_order(param_order_id, context).wait() { - Ok(rsp) => match rsp { - DeleteOrderResponse::InvalidIDSupplied => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - DeleteOrderResponse::OrderNotFound => { - - - let mut response = Response::with((status::Status::from_u16(404))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "DeleteOrder"); - - let api_clone = api.clone(); - router.get( - "/v2/store/inventory", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - let authorization = context.authorization.as_ref().ok_or_else(|| { - Response::with(( - status::Forbidden, - "Unauthenticated".to_string() - )) - })?; - - - - - - match api.get_inventory(context).wait() { - Ok(rsp) => match rsp { - GetInventoryResponse::SuccessfulOperation(body) => { - - let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - response.headers.set(ContentType(mimetypes::responses::GET_INVENTORY_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "GetInventory"); - - let api_clone = api.clone(); - router.get( - "/v2/store/order/:order_id", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - // Path parameters - let param_order_id = { - let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? - .find("order_id").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter order_id".to_string())))?; - percent_decode(param.as_bytes()).decode_utf8() - .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? - .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter order_id: {}", e))))? - }; - - - - match api.get_order_by_id(param_order_id, context).wait() { - Ok(rsp) => match rsp { - GetOrderByIdResponse::SuccessfulOperation(body) => { - - let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - response.headers.set(ContentType(mimetypes::responses::GET_ORDER_BY_ID_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - GetOrderByIdResponse::InvalidIDSupplied => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - GetOrderByIdResponse::OrderNotFound => { - - - let mut response = Response::with((status::Status::from_u16(404))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "GetOrderById"); - - let api_clone = api.clone(); - router.post( - "/v2/store/order", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; - - param_body - } else { - None - }; - let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; - - - match api.place_order(param_body, context).wait() { - Ok(rsp) => match rsp { - PlaceOrderResponse::SuccessfulOperation(body) => { - - let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - response.headers.set(ContentType(mimetypes::responses::PLACE_ORDER_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - PlaceOrderResponse::InvalidOrder => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "PlaceOrder"); - - let api_clone = api.clone(); - router.post( - "/v2/user", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; - - param_body - } else { - None - }; - let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; - - - match api.create_user(param_body, context).wait() { - Ok(rsp) => match rsp { - CreateUserResponse::SuccessfulOperation => { - - - let mut response = Response::with((status::Status::from_u16(0))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "CreateUser"); - - let api_clone = api.clone(); - router.post( - "/v2/user/createWithArray", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option> = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; - - param_body - } else { - None - }; - let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; - - - match api.create_users_with_array_input(param_body.as_ref(), context).wait() { - Ok(rsp) => match rsp { - CreateUsersWithArrayInputResponse::SuccessfulOperation => { - - - let mut response = Response::with((status::Status::from_u16(0))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "CreateUsersWithArrayInput"); - - let api_clone = api.clone(); - router.post( - "/v2/user/createWithList", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option> = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; - - param_body - } else { - None - }; - let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; - - - match api.create_users_with_list_input(param_body.as_ref(), context).wait() { - Ok(rsp) => match rsp { - CreateUsersWithListInputResponse::SuccessfulOperation => { - - - let mut response = Response::with((status::Status::from_u16(0))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "CreateUsersWithListInput"); - - let api_clone = api.clone(); - router.delete( - "/v2/user/:username", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - // Path parameters - let param_username = { - let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? - .find("username").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter username".to_string())))?; - percent_decode(param.as_bytes()).decode_utf8() - .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? - .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter username: {}", e))))? - }; - - - - match api.delete_user(param_username, context).wait() { - Ok(rsp) => match rsp { - DeleteUserResponse::InvalidUsernameSupplied => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - DeleteUserResponse::UserNotFound => { - - - let mut response = Response::with((status::Status::from_u16(404))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "DeleteUser"); - - let api_clone = api.clone(); - router.get( - "/v2/user/:username", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - // Path parameters - let param_username = { - let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? - .find("username").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter username".to_string())))?; - percent_decode(param.as_bytes()).decode_utf8() - .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? - .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter username: {}", e))))? - }; - - - - match api.get_user_by_name(param_username, context).wait() { - Ok(rsp) => match rsp { - GetUserByNameResponse::SuccessfulOperation(body) => { - - let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); - response.headers.set(ContentType(mimetypes::responses::GET_USER_BY_NAME_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - GetUserByNameResponse::InvalidUsernameSupplied => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - GetUserByNameResponse::UserNotFound => { - - - let mut response = Response::with((status::Status::from_u16(404))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "GetUserByName"); - - let api_clone = api.clone(); - router.get( - "/v2/user/login", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = req.get::().unwrap_or_default(); - let param_username = query_params.get("username") - .ok_or_else(|| Response::with((status::BadRequest, "Missing required query parameter username".to_string())))? - .first().ok_or_else(|| Response::with((status::BadRequest, "Required query parameter username was empty".to_string())))? - .parse::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse query parameter username - doesn't match schema: {}", e))))?; - let param_password = query_params.get("password") - .ok_or_else(|| Response::with((status::BadRequest, "Missing required query parameter password".to_string())))? - .first().ok_or_else(|| Response::with((status::BadRequest, "Required query parameter password was empty".to_string())))? - .parse::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse query parameter password - doesn't match schema: {}", e))))?; - - - match api.login_user(param_username, param_password, context).wait() { - Ok(rsp) => match rsp { - LoginUserResponse::SuccessfulOperation{ body, x_rate_limit, x_expires_after } => { - - let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - - let mut response = Response::with((status::Status::from_u16(200), body_string)); header! { (ResponseXRateLimit, "X-Rate-Limit") => [i32] } - response.headers.set(ResponseXRateLimit(x_rate_limit)); - header! { (ResponseXExpiresAfter, "X-Expires-After") => [chrono::DateTime] } - response.headers.set(ResponseXExpiresAfter(x_expires_after)); - - response.headers.set(ContentType(mimetypes::responses::LOGIN_USER_SUCCESSFUL_OPERATION.clone())); - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - LoginUserResponse::InvalidUsername => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "LoginUser"); - - let api_clone = api.clone(); - router.get( - "/v2/user/logout", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - - - match api.logout_user(context).wait() { - Ok(rsp) => match rsp { - LogoutUserResponse::SuccessfulOperation => { - - - let mut response = Response::with((status::Status::from_u16(0))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "LogoutUser"); - - let api_clone = api.clone(); - router.put( - "/v2/user/:username", - move |req: &mut Request| { - let mut context = Context::default(); - - // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). - fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { - - context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - context.auth_data = req.extensions.remove::(); - context.authorization = req.extensions.remove::(); - - - - // Path parameters - let param_username = { - let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? - .find("username").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter username".to_string())))?; - percent_decode(param.as_bytes()).decode_utf8() - .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? - .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter username: {}", e))))? - }; - - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - - let param_body = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; - - let mut unused_elements = Vec::new(); - - let param_body = if let Some(param_body_raw) = param_body { - let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); - - let param_body: Option = serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; - - param_body - } else { - None - }; - let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; - - - match api.update_user(param_username, param_body, context).wait() { - Ok(rsp) => match rsp { - UpdateUserResponse::InvalidUserSupplied => { - - - let mut response = Response::with((status::Status::from_u16(400))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - UpdateUserResponse::UserNotFound => { - - - let mut response = Response::with((status::Status::from_u16(404))); - - - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - if !unused_elements.is_empty() { - response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); - } - Ok(response) - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) - } - } - } - - handle_request(req, &api_clone, &mut context).or_else(|mut response| { - context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); - Ok(response) - }) - }, - "UpdateUser"); - -} - -/// Middleware to extract authentication data from request -pub struct ExtractAuthData; - -impl BeforeMiddleware for ExtractAuthData { - fn before(&self, req: &mut Request) -> IronResult<()> { - { - header! { (ApiKey1, "api_key") => [String] } - if let Some(header) = req.headers.get::() { - req.extensions.insert::(AuthData::ApiKey(header.0.clone())); - return Ok(()); - } - } - { - let header = match req.get_ref::() { - Ok(query) => query.get("api_key_query").map(|v| v[0].clone()), - _ => None - }; - if let Some(key) = header { - req.extensions.insert::(AuthData::ApiKey(key)); - return Ok(()); - } - } - { - use hyper::header::{Authorization, Basic, Bearer}; - use std::ops::Deref; - if let Some(basic) = req.headers.get::>() { - req.extensions.insert::(AuthData::Basic(basic.deref().clone())); - return Ok(()); - } - } - { - use hyper::header::{Authorization, Basic, Bearer}; - use std::ops::Deref; - if let Some(bearer) = req.headers.get::>() { - req.extensions.insert::(AuthData::Bearer(bearer.deref().clone())); - return Ok(()); - } - } - - Ok(()) - } -} diff --git a/samples/server/petstore/rust-server/src/server/auth.rs b/samples/server/petstore/rust-server/src/server/auth.rs new file mode 100644 index 000000000000..5c120b74c7c4 --- /dev/null +++ b/samples/server/petstore/rust-server/src/server/auth.rs @@ -0,0 +1,83 @@ +use std::io; +use hyper; +use hyper::{Request, Response, Error, StatusCode}; +use server::url::form_urlencoded; +use swagger::auth::{Authorization, AuthData, Scopes}; +use Api; + +pub struct NewService where T: hyper::server::NewService), Response=Response, Error=Error> { + inner: T, +} + +impl NewService where T: hyper::server::NewService), Response=Response, Error=Error> + 'static { + pub fn new(inner: T) -> NewService { + NewService{inner} + } +} + +impl hyper::server::NewService for NewService where T: hyper::server::NewService), Response=Response, Error=Error> + 'static { + type Request = Request; + type Response = Response; + type Error = Error; + type Instance = Service; + + fn new_service(&self) -> Result { + self.inner.new_service().map(|s| Service::new(s)) + } +} + +/// Middleware to extract authentication data from request +pub struct Service where T: hyper::server::Service), Response=Response, Error=Error> { + inner: T, +} + +impl Service where T: hyper::server::Service), Response=Response, Error=Error> { + pub fn new(inner: T) -> Service { + Service{inner} + } +} + +impl hyper::server::Service for Service where T: hyper::server::Service), Response=Response, Error=Error> { + type Request = Request; + type Response = Response; + type Error = Error; + type Future = T::Future; + + fn call(&self, req: Self::Request) -> Self::Future { + { + header! { (ApiKey1, "api_key") => [String] } + if let Some(header) = req.headers().get::().cloned() { + let auth_data = AuthData::ApiKey(header.0); + return self.inner.call((req, Some(auth_data))); + } + } + { + let key = form_urlencoded::parse(req.query().unwrap_or_default().as_bytes()) + .filter(|e| e.0 == "api_key_query") + .map(|e| e.1.clone().into_owned()) + .nth(0); + if let Some(key) = key { + let auth_data = AuthData::ApiKey(key); + return self.inner.call((req, Some(auth_data))); + } + } + { + use hyper::header::{Authorization, Basic, Bearer}; + use std::ops::Deref; + if let Some(basic) = req.headers().get::>().cloned() { + let auth_data = AuthData::Basic(basic.deref().clone()); + return self.inner.call((req, Some(auth_data))); + } + } + { + use hyper::header::{Authorization, Basic, Bearer}; + use std::ops::Deref; + if let Some(bearer) = req.headers().get::>().cloned() { + let auth_data = AuthData::Bearer(bearer.deref().clone()); + return self.inner.call((req, Some(auth_data))); + } + } + + return self.inner.call((req, None)); + } +} diff --git a/samples/server/petstore/rust-server/src/server/mod.rs b/samples/server/petstore/rust-server/src/server/mod.rs new file mode 100644 index 000000000000..7f88b6b3ad8e --- /dev/null +++ b/samples/server/petstore/rust-server/src/server/mod.rs @@ -0,0 +1,3058 @@ +#![allow(unused_extern_crates)] +extern crate serde_ignored; +extern crate tokio_core; +extern crate native_tls; +extern crate hyper_tls; +extern crate openssl; +extern crate mime; +extern crate uuid; +extern crate chrono; +extern crate multipart; +extern crate percent_encoding; +extern crate url; + + +use std::sync::Arc; +use futures::{Future, future, Stream, stream}; +use hyper; +use hyper::{Request, Response, Error, StatusCode}; +use hyper::header::{Headers, ContentType}; +use self::url::form_urlencoded; +use mimetypes; +use self::multipart::server::Multipart; +use self::multipart::server::save::SaveResult; + +use serde_json; +use serde_xml_rs; + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; +use std::io; + +#[allow(unused_imports)] +use std::collections::BTreeSet; + +pub use swagger::auth::Authorization; +use swagger::{ApiError, Context, XSpanId}; +use swagger::auth::Scopes; + +use {Api, + TestSpecialTagsResponse, + TestBodyWithQueryParamsResponse, + FakeOuterBooleanSerializeResponse, + FakeOuterCompositeSerializeResponse, + FakeOuterNumberSerializeResponse, + FakeOuterStringSerializeResponse, + TestClientModelResponse, + TestEndpointParametersResponse, + TestEnumParametersResponse, + TestInlineAdditionalPropertiesResponse, + TestJsonFormDataResponse, + TestClassnameResponse, + AddPetResponse, + DeletePetResponse, + FindPetsByStatusResponse, + FindPetsByTagsResponse, + GetPetByIdResponse, + UpdatePetResponse, + UpdatePetWithFormResponse, + UploadFileResponse, + DeleteOrderResponse, + GetInventoryResponse, + GetOrderByIdResponse, + PlaceOrderResponse, + CreateUserResponse, + CreateUsersWithArrayInputResponse, + CreateUsersWithListInputResponse, + DeleteUserResponse, + GetUserByNameResponse, + LoginUserResponse, + LogoutUserResponse, + UpdateUserResponse + }; +#[allow(unused_imports)] +use models; + +pub mod auth; + +header! { (Warning, "Warning") => [String] } + +mod paths { + extern crate regex; + + lazy_static! { + pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(&[ + r"^/v2/another-fake/dummy$", + r"^/v2/fake$", + r"^/v2/fake/body-with-query-params$", + r"^/v2/fake/inline-additionalProperties$", + r"^/v2/fake/jsonFormData$", + r"^/v2/fake/outer/boolean$", + r"^/v2/fake/outer/composite$", + r"^/v2/fake/outer/number$", + r"^/v2/fake/outer/string$", + r"^/v2/fake_classname_test$", + r"^/v2/pet$", + r"^/v2/pet/findByStatus$", + r"^/v2/pet/findByTags$", + r"^/v2/pet/(?P[^/?#]*)$", + r"^/v2/pet/(?P[^/?#]*)/uploadImage$", + r"^/v2/store/inventory$", + r"^/v2/store/order$", + r"^/v2/store/order/(?P[^/?#]*)$", + r"^/v2/user$", + r"^/v2/user/createWithArray$", + r"^/v2/user/createWithList$", + r"^/v2/user/login$", + r"^/v2/user/logout$", + r"^/v2/user/(?P[^/?#]*)$" + ]).unwrap(); + } + pub static ID_ANOTHER_FAKE_DUMMY: usize = 0; + pub static ID_FAKE: usize = 1; + pub static ID_FAKE_BODY_WITH_QUERY_PARAMS: usize = 2; + pub static ID_FAKE_INLINE_ADDITIONALPROPERTIES: usize = 3; + pub static ID_FAKE_JSONFORMDATA: usize = 4; + pub static ID_FAKE_OUTER_BOOLEAN: usize = 5; + pub static ID_FAKE_OUTER_COMPOSITE: usize = 6; + pub static ID_FAKE_OUTER_NUMBER: usize = 7; + pub static ID_FAKE_OUTER_STRING: usize = 8; + pub static ID_FAKE_CLASSNAME_TEST: usize = 9; + pub static ID_PET: usize = 10; + pub static ID_PET_FINDBYSTATUS: usize = 11; + pub static ID_PET_FINDBYTAGS: usize = 12; + pub static ID_PET_PETID: usize = 13; + lazy_static! { + pub static ref REGEX_PET_PETID: regex::Regex = regex::Regex::new(r"^/v2/pet/(?P[^/?#]*)$").unwrap(); + } + pub static ID_PET_PETID_UPLOADIMAGE: usize = 14; + lazy_static! { + pub static ref REGEX_PET_PETID_UPLOADIMAGE: regex::Regex = regex::Regex::new(r"^/v2/pet/(?P[^/?#]*)/uploadImage$").unwrap(); + } + pub static ID_STORE_INVENTORY: usize = 15; + pub static ID_STORE_ORDER: usize = 16; + pub static ID_STORE_ORDER_ORDER_ID: usize = 17; + lazy_static! { + pub static ref REGEX_STORE_ORDER_ORDER_ID: regex::Regex = regex::Regex::new(r"^/v2/store/order/(?P[^/?#]*)$").unwrap(); + } + pub static ID_USER: usize = 18; + pub static ID_USER_CREATEWITHARRAY: usize = 19; + pub static ID_USER_CREATEWITHLIST: usize = 20; + pub static ID_USER_LOGIN: usize = 21; + pub static ID_USER_LOGOUT: usize = 22; + pub static ID_USER_USERNAME: usize = 23; + lazy_static! { + pub static ref REGEX_USER_USERNAME: regex::Regex = regex::Regex::new(r"^/v2/user/(?P[^/?#]*)$").unwrap(); + } +} + +pub struct NewService { + api_impl: Arc, +} + +impl NewService where T: Api + Clone + 'static { + pub fn new>>(api_impl: U) -> NewService { + NewService{api_impl: api_impl.into()} + } +} + +impl hyper::server::NewService for NewService where T: Api + Clone + 'static { + type Request = (Request, Context); + type Response = Response; + type Error = Error; + type Instance = Service; + + fn new_service(&self) -> Result { + Ok(Service::new(self.api_impl.clone())) + } +} + +pub struct Service { + api_impl: Arc, +} + +impl Service where T: Api + Clone + 'static { + pub fn new>>(api_impl: U) -> Service { + Service{api_impl: api_impl.into()} + } +} + +impl hyper::server::Service for Service where T: Api + Clone + 'static { + type Request = (Request, Context); + type Response = Response; + type Error = Error; + type Future = Box>; + + fn call(&self, (req, mut context): Self::Request) -> Self::Future { + let api_impl = self.api_impl.clone(); + let (method, uri, _, headers, body) = req.deconstruct(); + let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); + match &method { + + // TestSpecialTags - PATCH /another-fake/dummy + &hyper::Method::Patch if path.matched(paths::ID_ANOTHER_FAKE_DUMMY) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; + + + Box::new(api_impl.test_special_tags(param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + TestSpecialTagsResponse::SuccessfulOperation + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::TEST_SPECIAL_TAGS_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // TestBodyWithQueryParams - PUT /fake/body-with-query-params + &hyper::Method::Put if path.matched(paths::ID_FAKE_BODY_WITH_QUERY_PARAMS) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); + let param_query = query_params.iter().filter(|e| e.0 == "query").map(|e| e.1.to_owned()) + + .nth(0); + let param_query = match param_query { + Some(param_query) => match param_query.parse::() { + Ok(param_query) => param_query, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse query parameter query - doesn't match schema: {}", e)))), + }, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required query parameter query"))), + }; + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; + + + Box::new(api_impl.test_body_with_query_params(param_body, param_query, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + TestBodyWithQueryParamsResponse::Success + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // FakeOuterBooleanSerialize - POST /fake/outer/boolean + &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_BOOLEAN) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + + Err(_) => None, + } + + } else { + None + }; + + + Box::new(api_impl.fake_outer_boolean_serialize(param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + FakeOuterBooleanSerializeResponse::OutputBoolean + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // FakeOuterCompositeSerialize - POST /fake/outer/composite + &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_COMPOSITE) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + + Err(_) => None, + } + + } else { + None + }; + + + Box::new(api_impl.fake_outer_composite_serialize(param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + FakeOuterCompositeSerializeResponse::OutputComposite + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // FakeOuterNumberSerialize - POST /fake/outer/number + &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_NUMBER) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + + Err(_) => None, + } + + } else { + None + }; + + + Box::new(api_impl.fake_outer_number_serialize(param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + FakeOuterNumberSerializeResponse::OutputNumber + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // FakeOuterStringSerialize - POST /fake/outer/string + &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_STRING) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + + Err(_) => None, + } + + } else { + None + }; + + + Box::new(api_impl.fake_outer_string_serialize(param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + FakeOuterStringSerializeResponse::OutputString + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // TestClientModel - PATCH /fake + &hyper::Method::Patch if path.matched(paths::ID_FAKE) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; + + + Box::new(api_impl.test_client_model(param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + TestClientModelResponse::SuccessfulOperation + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::TEST_CLIENT_MODEL_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // TestEndpointParameters - POST /fake + &hyper::Method::Post if path.matched(paths::ID_FAKE) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + } + + + + + + + + Box::new(({ + {{ + + // Form parameters + let param_integer = Some(56); + let param_int32 = Some(56); + let param_int64 = Some(789); + let param_number = 8.14; + let param_float = Some(3.4); + let param_double = 1.2; + let param_string = Some("string_example".to_string()); + let param_pattern_without_delimiter = "pattern_without_delimiter_example".to_string(); + let param_byte = swagger::ByteArray(Vec::from("B")); + let param_binary = Some(swagger::ByteArray(Vec::from("B"))); + let param_date = None; + let param_date_time = None; + let param_password = Some("password_example".to_string()); + let param_callback = Some("callback_example".to_string()); + + Box::new(api_impl.test_endpoint_parameters(param_number, param_double, param_pattern_without_delimiter, param_byte, param_integer, param_int32, param_int64, param_float, param_string, param_binary, param_date, param_date_time, param_password, param_callback, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + TestEndpointParametersResponse::InvalidUsernameSupplied + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + TestEndpointParametersResponse::UserNotFound + + + => { + response.set_status(StatusCode::try_from(404).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // TestEnumParameters - GET /fake + &hyper::Method::Get if path.matched(paths::ID_FAKE) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + // Header parameters + header! { (RequestEnumHeaderStringArray, "enum_header_string_array") => (String)* } + let param_enum_header_string_array = headers.get::().map(|header| header.0.clone()); + header! { (RequestEnumHeaderString, "enum_header_string") => [String] } + let param_enum_header_string = headers.get::().map(|header| header.0.clone()); + + + + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); + let param_enum_query_string_array = query_params.iter().filter(|e| e.0 == "enum_query_string_array").map(|e| e.1.to_owned()) + .filter_map(|param_enum_query_string_array| param_enum_query_string_array.parse::().ok()) + .collect::>(); + let param_enum_query_string_array = if !param_enum_query_string_array.is_empty() { + Some(param_enum_query_string_array) + } else { + None + }; + let param_enum_query_string = query_params.iter().filter(|e| e.0 == "enum_query_string").map(|e| e.1.to_owned()) + + .nth(0); + + let param_enum_query_string = param_enum_query_string.and_then(|param_enum_query_string| param_enum_query_string.parse::<>().ok()); + let param_enum_query_integer = query_params.iter().filter(|e| e.0 == "enum_query_integer").map(|e| e.1.to_owned()) + + .nth(0); + + let param_enum_query_integer = param_enum_query_integer.and_then(|param_enum_query_integer| param_enum_query_integer.parse::<>().ok()); + + + + Box::new(({ + {{ + + // Form parameters + let param_enum_form_string_array = None; + let param_enum_form_string = Some("enum_form_string_example".to_string()); + let param_enum_query_double = Some(1.2); + + Box::new(api_impl.test_enum_parameters(param_enum_form_string_array.as_ref(), param_enum_form_string, param_enum_header_string_array.as_ref(), param_enum_header_string, param_enum_query_string_array.as_ref(), param_enum_query_string, param_enum_query_integer, param_enum_query_double, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + TestEnumParametersResponse::InvalidRequest + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + TestEnumParametersResponse::NotFound + + + => { + response.set_status(StatusCode::try_from(404).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // TestInlineAdditionalProperties - POST /fake/inline-additionalProperties + &hyper::Method::Post if path.matched(paths::ID_FAKE_INLINE_ADDITIONALPROPERTIES) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_param: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_param) => param_param, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter param - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_param = match param_param { + Some(param_param) => param_param, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter param"))), + }; + + + Box::new(api_impl.test_inline_additional_properties(param_param, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + TestInlineAdditionalPropertiesResponse::SuccessfulOperation + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter param: {}", e)))), + } + }) + ) as Box> + + }, + + + // TestJsonFormData - GET /fake/jsonFormData + &hyper::Method::Get if path.matched(paths::ID_FAKE_JSONFORMDATA) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + + Box::new(({ + {{ + + // Form parameters + let param_param = "param_example".to_string(); + let param_param2 = "param2_example".to_string(); + + Box::new(api_impl.test_json_form_data(param_param, param_param2, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + TestJsonFormDataResponse::SuccessfulOperation + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // TestClassname - PATCH /fake_classname_test + &hyper::Method::Patch if path.matched(paths::ID_FAKE_CLASSNAME_TEST) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; + + + Box::new(api_impl.test_classname(param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + TestClassnameResponse::SuccessfulOperation + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::TEST_CLASSNAME_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // AddPet - POST /pet + &hyper::Method::Post if path.matched(paths::ID_PET) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body(missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + )) + )); + } + } + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; + + + Box::new(api_impl.add_pet(param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + AddPetResponse::InvalidInput + + + => { + response.set_status(StatusCode::try_from(405).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // DeletePet - DELETE /pet/{petId} + &hyper::Method::Delete if path.matched(paths::ID_PET_PETID) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body(missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + )) + )); + } + } + } + + + // Path parameters + let path = uri.path().to_string(); + let path_params = + paths::REGEX_PET_PETID + .captures(&path) + .unwrap_or_else(|| + panic!("Path {} matched RE PET_PETID in set but failed match against \"{}\"", path, paths::REGEX_PET_PETID.as_str()) + ); + + let param_pet_id = match percent_encoding::percent_decode(path_params["petId"].as_bytes()).decode_utf8() { + Ok(param_pet_id) => match param_pet_id.parse::() { + Ok(param_pet_id) => param_pet_id, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter petId: {}", e)))), + }, + Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["petId"])))) + }; + + // Header parameters + header! { (RequestApiKey, "api_key") => [String] } + let param_api_key = headers.get::().map(|header| header.0.clone()); + + + + + + Box::new(({ + {{ + + Box::new(api_impl.delete_pet(param_pet_id, param_api_key, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + DeletePetResponse::InvalidPetValue + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // FindPetsByStatus - GET /pet/findByStatus + &hyper::Method::Get if path.matched(paths::ID_PET_FINDBYSTATUS) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body(missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + )) + )); + } + } + } + + + + + + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); + let param_status = query_params.iter().filter(|e| e.0 == "status").map(|e| e.1.to_owned()) + .filter_map(|param_status| param_status.parse::().ok()) + .collect::>(); + + + + Box::new(({ + {{ + + Box::new(api_impl.find_pets_by_status(param_status.as_ref(), &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + FindPetsByStatusResponse::SuccessfulOperation + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::FIND_PETS_BY_STATUS_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + FindPetsByStatusResponse::InvalidStatusValue + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // FindPetsByTags - GET /pet/findByTags + &hyper::Method::Get if path.matched(paths::ID_PET_FINDBYTAGS) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body(missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + )) + )); + } + } + } + + + + + + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); + let param_tags = query_params.iter().filter(|e| e.0 == "tags").map(|e| e.1.to_owned()) + .filter_map(|param_tags| param_tags.parse::().ok()) + .collect::>(); + + + + Box::new(({ + {{ + + Box::new(api_impl.find_pets_by_tags(param_tags.as_ref(), &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + FindPetsByTagsResponse::SuccessfulOperation + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::FIND_PETS_BY_TAGS_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + FindPetsByTagsResponse::InvalidTagValue + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // GetPetById - GET /pet/{petId} + &hyper::Method::Get if path.matched(paths::ID_PET_PETID) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + } + + + // Path parameters + let path = uri.path().to_string(); + let path_params = + paths::REGEX_PET_PETID + .captures(&path) + .unwrap_or_else(|| + panic!("Path {} matched RE PET_PETID in set but failed match against \"{}\"", path, paths::REGEX_PET_PETID.as_str()) + ); + + let param_pet_id = match percent_encoding::percent_decode(path_params["petId"].as_bytes()).decode_utf8() { + Ok(param_pet_id) => match param_pet_id.parse::() { + Ok(param_pet_id) => param_pet_id, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter petId: {}", e)))), + }, + Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["petId"])))) + }; + + + + + + Box::new(({ + {{ + + Box::new(api_impl.get_pet_by_id(param_pet_id, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + GetPetByIdResponse::SuccessfulOperation + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::GET_PET_BY_ID_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + GetPetByIdResponse::InvalidIDSupplied + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + GetPetByIdResponse::PetNotFound + + + => { + response.set_status(StatusCode::try_from(404).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // UpdatePet - PUT /pet + &hyper::Method::Put if path.matched(paths::ID_PET) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body(missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + )) + )); + } + } + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; + + + Box::new(api_impl.update_pet(param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + UpdatePetResponse::InvalidIDSupplied + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + UpdatePetResponse::PetNotFound + + + => { + response.set_status(StatusCode::try_from(404).unwrap()); + + }, + UpdatePetResponse::ValidationException + + + => { + response.set_status(StatusCode::try_from(405).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // UpdatePetWithForm - POST /pet/{petId} + &hyper::Method::Post if path.matched(paths::ID_PET_PETID) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body(missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + )) + )); + } + } + } + + + // Path parameters + let path = uri.path().to_string(); + let path_params = + paths::REGEX_PET_PETID + .captures(&path) + .unwrap_or_else(|| + panic!("Path {} matched RE PET_PETID in set but failed match against \"{}\"", path, paths::REGEX_PET_PETID.as_str()) + ); + + let param_pet_id = match percent_encoding::percent_decode(path_params["petId"].as_bytes()).decode_utf8() { + Ok(param_pet_id) => match param_pet_id.parse::() { + Ok(param_pet_id) => param_pet_id, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter petId: {}", e)))), + }, + Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["petId"])))) + }; + + + + + + Box::new(({ + {{ + + // Form parameters + let param_name = Some("name_example".to_string()); + let param_status = Some("status_example".to_string()); + + Box::new(api_impl.update_pet_with_form(param_pet_id, param_name, param_status, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + UpdatePetWithFormResponse::InvalidInput + + + => { + response.set_status(StatusCode::try_from(405).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // UploadFile - POST /pet/{petId}/uploadImage + &hyper::Method::Post if path.matched(paths::ID_PET_PETID_UPLOADIMAGE) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body(missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + )) + )); + } + } + } + + + // Path parameters + let path = uri.path().to_string(); + let path_params = + paths::REGEX_PET_PETID_UPLOADIMAGE + .captures(&path) + .unwrap_or_else(|| + panic!("Path {} matched RE PET_PETID_UPLOADIMAGE in set but failed match against \"{}\"", path, paths::REGEX_PET_PETID_UPLOADIMAGE.as_str()) + ); + + let param_pet_id = match percent_encoding::percent_decode(path_params["petId"].as_bytes()).decode_utf8() { + Ok(param_pet_id) => match param_pet_id.parse::() { + Ok(param_pet_id) => param_pet_id, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter petId: {}", e)))), + }, + Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["petId"])))) + }; + + + + + + let boundary = match multipart_boundary(&headers) { + Some(boundary) => boundary.to_string(), + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Couldn't find valid multipart body"))), + }; + + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + let mut entries = match Multipart::with_body(&body.to_vec()[..], boundary).save().temp() { + SaveResult::Full(entries) => { + entries + }, + _ => { + return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Unable to process all message parts")))) + }, + }; + + // Form parameters + let param_additional_metadata = entries.fields.remove("additional_metadata"); + let param_additional_metadata = match param_additional_metadata { + Some(entry) => + + match entry.parse::() { + Ok(entry) => Some(entry), + + Err(_) => None, + }, + + None => None, + }; + + let param_file = entries.fields.remove("file"); + let param_file = match param_file { + Some(entry) => + Some(Box::new(stream::once(Ok(entry.as_bytes().to_vec()))) as Box, Error=io::Error> + Send>), + + None => None, + }; + let param_file = Box::new(future::ok(param_file)); + + Box::new(api_impl.upload_file(param_pet_id, param_additional_metadata, param_file, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + UploadFileResponse::SuccessfulOperation + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::UPLOAD_FILE_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + as Box> + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read multipart body")))), + } + }) + ) + + + }, + + + // DeleteOrder - DELETE /store/order/{order_id} + &hyper::Method::Delete if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + // Path parameters + let path = uri.path().to_string(); + let path_params = + paths::REGEX_STORE_ORDER_ORDER_ID + .captures(&path) + .unwrap_or_else(|| + panic!("Path {} matched RE STORE_ORDER_ORDER_ID in set but failed match against \"{}\"", path, paths::REGEX_STORE_ORDER_ORDER_ID.as_str()) + ); + + let param_order_id = match percent_encoding::percent_decode(path_params["order_id"].as_bytes()).decode_utf8() { + Ok(param_order_id) => match param_order_id.parse::() { + Ok(param_order_id) => param_order_id, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter order_id: {}", e)))), + }, + Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["order_id"])))) + }; + + + + + + Box::new(({ + {{ + + Box::new(api_impl.delete_order(param_order_id, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + DeleteOrderResponse::InvalidIDSupplied + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + DeleteOrderResponse::OrderNotFound + + + => { + response.set_status(StatusCode::try_from(404).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // GetInventory - GET /store/inventory + &hyper::Method::Get if path.matched(paths::ID_STORE_INVENTORY) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + { + let authorization = match context.authorization.as_ref() { + Some(authorization) => authorization, + None => return Box::new(future::ok(Response::new() + .with_status(StatusCode::Forbidden) + .with_body("Unauthenticated"))), + }; + + } + + + + + + + + Box::new(({ + {{ + + Box::new(api_impl.get_inventory(&context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + GetInventoryResponse::SuccessfulOperation + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::GET_INVENTORY_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // GetOrderById - GET /store/order/{order_id} + &hyper::Method::Get if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + // Path parameters + let path = uri.path().to_string(); + let path_params = + paths::REGEX_STORE_ORDER_ORDER_ID + .captures(&path) + .unwrap_or_else(|| + panic!("Path {} matched RE STORE_ORDER_ORDER_ID in set but failed match against \"{}\"", path, paths::REGEX_STORE_ORDER_ORDER_ID.as_str()) + ); + + let param_order_id = match percent_encoding::percent_decode(path_params["order_id"].as_bytes()).decode_utf8() { + Ok(param_order_id) => match param_order_id.parse::() { + Ok(param_order_id) => param_order_id, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter order_id: {}", e)))), + }, + Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["order_id"])))) + }; + + + + + + Box::new(({ + {{ + + Box::new(api_impl.get_order_by_id(param_order_id, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + GetOrderByIdResponse::SuccessfulOperation + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::GET_ORDER_BY_ID_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + GetOrderByIdResponse::InvalidIDSupplied + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + GetOrderByIdResponse::OrderNotFound + + + => { + response.set_status(StatusCode::try_from(404).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // PlaceOrder - POST /store/order + &hyper::Method::Post if path.matched(paths::ID_STORE_ORDER) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; + + + Box::new(api_impl.place_order(param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + PlaceOrderResponse::SuccessfulOperation + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::PLACE_ORDER_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + PlaceOrderResponse::InvalidOrder + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // CreateUser - POST /user + &hyper::Method::Post if path.matched(paths::ID_USER) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; + + + Box::new(api_impl.create_user(param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + CreateUserResponse::SuccessfulOperation + + + => { + response.set_status(StatusCode::try_from(0).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // CreateUsersWithArrayInput - POST /user/createWithArray + &hyper::Method::Post if path.matched(paths::ID_USER_CREATEWITHARRAY) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option> = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; + + + Box::new(api_impl.create_users_with_array_input(param_body.as_ref(), &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + CreateUsersWithArrayInputResponse::SuccessfulOperation + + + => { + response.set_status(StatusCode::try_from(0).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // CreateUsersWithListInput - POST /user/createWithList + &hyper::Method::Post if path.matched(paths::ID_USER_CREATEWITHLIST) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option> = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; + + + Box::new(api_impl.create_users_with_list_input(param_body.as_ref(), &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + CreateUsersWithListInputResponse::SuccessfulOperation + + + => { + response.set_status(StatusCode::try_from(0).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + // DeleteUser - DELETE /user/{username} + &hyper::Method::Delete if path.matched(paths::ID_USER_USERNAME) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + // Path parameters + let path = uri.path().to_string(); + let path_params = + paths::REGEX_USER_USERNAME + .captures(&path) + .unwrap_or_else(|| + panic!("Path {} matched RE USER_USERNAME in set but failed match against \"{}\"", path, paths::REGEX_USER_USERNAME.as_str()) + ); + + let param_username = match percent_encoding::percent_decode(path_params["username"].as_bytes()).decode_utf8() { + Ok(param_username) => match param_username.parse::() { + Ok(param_username) => param_username, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter username: {}", e)))), + }, + Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["username"])))) + }; + + + + + + Box::new(({ + {{ + + Box::new(api_impl.delete_user(param_username, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + DeleteUserResponse::InvalidUsernameSupplied + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + DeleteUserResponse::UserNotFound + + + => { + response.set_status(StatusCode::try_from(404).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // GetUserByName - GET /user/{username} + &hyper::Method::Get if path.matched(paths::ID_USER_USERNAME) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + // Path parameters + let path = uri.path().to_string(); + let path_params = + paths::REGEX_USER_USERNAME + .captures(&path) + .unwrap_or_else(|| + panic!("Path {} matched RE USER_USERNAME in set but failed match against \"{}\"", path, paths::REGEX_USER_USERNAME.as_str()) + ); + + let param_username = match percent_encoding::percent_decode(path_params["username"].as_bytes()).decode_utf8() { + Ok(param_username) => match param_username.parse::() { + Ok(param_username) => param_username, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter username: {}", e)))), + }, + Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["username"])))) + }; + + + + + + Box::new(({ + {{ + + Box::new(api_impl.get_user_by_name(param_username, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + GetUserByNameResponse::SuccessfulOperation + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::GET_USER_BY_NAME_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + GetUserByNameResponse::InvalidUsernameSupplied + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + GetUserByNameResponse::UserNotFound + + + => { + response.set_status(StatusCode::try_from(404).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // LoginUser - GET /user/login + &hyper::Method::Get if path.matched(paths::ID_USER_LOGIN) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); + let param_username = query_params.iter().filter(|e| e.0 == "username").map(|e| e.1.to_owned()) + + .nth(0); + let param_username = match param_username { + Some(param_username) => match param_username.parse::() { + Ok(param_username) => param_username, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse query parameter username - doesn't match schema: {}", e)))), + }, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required query parameter username"))), + }; + let param_password = query_params.iter().filter(|e| e.0 == "password").map(|e| e.1.to_owned()) + + .nth(0); + let param_password = match param_password { + Some(param_password) => match param_password.parse::() { + Ok(param_password) => param_password, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse query parameter password - doesn't match schema: {}", e)))), + }, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required query parameter password"))), + }; + + + + Box::new(({ + {{ + + Box::new(api_impl.login_user(param_username, param_password, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + LoginUserResponse::SuccessfulOperation + + { + body, + x_rate_limit, + + x_expires_after + } + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + header! { (ResponseXRateLimit, "X-Rate-Limit") => [i32] } + response.headers_mut().set(ResponseXRateLimit(x_rate_limit)); + header! { (ResponseXExpiresAfter, "X-Expires-After") => [chrono::DateTime] } + response.headers_mut().set(ResponseXExpiresAfter(x_expires_after)); + + response.headers_mut().set(ContentType(mimetypes::responses::LOGIN_USER_SUCCESSFUL_OPERATION.clone())); + + + let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + LoginUserResponse::InvalidUsername + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // LogoutUser - GET /user/logout + &hyper::Method::Get if path.matched(paths::ID_USER_LOGOUT) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + + + + + + Box::new(({ + {{ + + Box::new(api_impl.logout_user(&context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + match result { + Ok(rsp) => match rsp { + LogoutUserResponse::SuccessfulOperation + + + => { + response.set_status(StatusCode::try_from(0).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + }} + })) as Box> + + + }, + + + // UpdateUser - PUT /user/{username} + &hyper::Method::Put if path.matched(paths::ID_USER_USERNAME) => { + if context.x_span_id.is_none() { + context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + } + + + // Path parameters + let path = uri.path().to_string(); + let path_params = + paths::REGEX_USER_USERNAME + .captures(&path) + .unwrap_or_else(|| + panic!("Path {} matched RE USER_USERNAME in set but failed match against \"{}\"", path, paths::REGEX_USER_USERNAME.as_str()) + ); + + let param_username = match percent_encoding::percent_decode(path_params["username"].as_bytes()).decode_utf8() { + Ok(param_username) => match param_username.parse::() { + Ok(param_username) => param_username, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter username: {}", e)))), + }, + Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["username"])))) + }; + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_body: Option = if !body.is_empty() { + + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; + + + Box::new(api_impl.update_user(param_username, param_body, &context) + .then(move |result| { + let mut response = Response::new(); + context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + UpdateUserResponse::InvalidUserSupplied + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + UpdateUserResponse::UserNotFound + + + => { + response.set_status(StatusCode::try_from(404).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + } + }) + ) as Box> + + }, + + + _ => Box::new(future::ok(Response::new().with_status(StatusCode::NotFound))) as Box>, + } + } +} + +/// Utility function to get the multipart boundary marker (if any) from the Headers. +fn multipart_boundary<'a>(headers: &'a Headers) -> Option<&'a str> { + headers.get::().and_then(|content_type| { + let ContentType(ref mime) = *content_type; + if mime.type_() == mime::MULTIPART && mime.subtype() == mime::FORM_DATA { + mime.get_param(mime::BOUNDARY).map(|x| x.as_str()) + } else { + None + } + }) +} diff --git a/samples/server/petstore/sinatra/.swagger-codegen/VERSION b/samples/server/petstore/sinatra/.swagger-codegen/VERSION index 7fea99011a6f..096bf47efe31 100644 --- a/samples/server/petstore/sinatra/.swagger-codegen/VERSION +++ b/samples/server/petstore/sinatra/.swagger-codegen/VERSION @@ -1 +1 @@ -2.2.3-SNAPSHOT \ No newline at end of file +3.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/sinatra/api/pet_api.rb b/samples/server/petstore/sinatra/api/pet_api.rb index e2bb229218b1..39fa701c8111 100644 --- a/samples/server/petstore/sinatra/api/pet_api.rb +++ b/samples/server/petstore/sinatra/api/pet_api.rb @@ -63,10 +63,8 @@ "name" => "status", "description" => "Status values that need to be considered for filter", "dataType" => "array[string]", - "paramType" => "query", "collectionFormat" => "csv", - "allowableValues" => "", - + "paramType" => "query", }, ]}) do cross_origin @@ -88,10 +86,8 @@ "name" => "tags", "description" => "Tags to filter by", "dataType" => "array[string]", - "paramType" => "query", "collectionFormat" => "csv", - "allowableValues" => "", - + "paramType" => "query", }, ]}) do cross_origin diff --git a/samples/server/petstore/sinatra/api/user_api.rb b/samples/server/petstore/sinatra/api/user_api.rb index bfec8909586d..f2f159ead6d4 100644 --- a/samples/server/petstore/sinatra/api/user_api.rb +++ b/samples/server/petstore/sinatra/api/user_api.rb @@ -99,7 +99,7 @@ "parameters" => [ { "name" => "username", - "description" => "The name that needs to be fetched. Use user1 for testing. ", + "description" => "The name that needs to be fetched. Use user1 for testing.", "dataType" => "string", "paramType" => "path", }, @@ -123,19 +123,15 @@ "name" => "username", "description" => "The user name for login", "dataType" => "string", - "paramType" => "query", - "allowableValues" => "", - + "paramType" => "query", }, { "name" => "password", "description" => "The password for login in clear text", "dataType" => "string", - "paramType" => "query", - "allowableValues" => "", - + "paramType" => "query", }, ]}) do cross_origin diff --git a/samples/server/petstore/sinatra/openapi.yaml b/samples/server/petstore/sinatra/openapi.yaml new file mode 100644 index 000000000000..3c412357c808 --- /dev/null +++ b/samples/server/petstore/sinatra/openapi.yaml @@ -0,0 +1,764 @@ +openapi: 3.0.0 +info: + title: Swagger Petstore + description: 'This is a sample server Petstore server. You can find out more about + Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For + this sample, you can use the api key `special-key` to test the authorization filters.' + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache-2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.0 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: +- url: http://petstore.swagger.io/v2 +tags: +- name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io +- name: store + description: Access to Petstore orders +- name: user + description: Operations about user + externalDocs: + description: Find out more about our store + url: http://swagger.io +paths: + /pet: + put: + tags: + - pet + summary: Update an existing pet + operationId: updatePet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + 400: + description: Invalid ID supplied + 404: + description: Pet not found + 405: + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + post: + tags: + - pet + summary: Add a new pet to the store + operationId: addPet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + 405: + description: Invalid input + 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 + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + schema: + type: array + items: + type: string + default: available + enum: + - available + - pending + - sold + responses: + 200: + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/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 + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + 200: + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + 400: + description: Invalid tag value + deprecated: true + security: + - petstore_auth: + - write:pets + - read:pets + /pet/{petId}: + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/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 + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + style: simple + explode: false + schema: + type: integer + format: int64 + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/body' + responses: + 405: + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + delete: + tags: + - pet + summary: Deletes a pet + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + style: simple + explode: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + style: simple + explode: false + schema: + 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 + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + style: simple + explode: false + schema: + type: integer + format: int64 + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/body_1' + responses: + 200: + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/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 + responses: + 200: + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + operationId: placeOrder + requestBody: + description: order placed for purchasing the pet + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + required: true + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/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 + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + style: simple + explode: false + schema: + maximum: 5 + minimum: 1 + type: integer + format: int64 + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/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 + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + style: simple + explode: false + schema: + 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 + requestBody: + description: Created user object + content: + application/json: + schema: + $ref: '#/components/schemas/User' + required: true + responses: + default: + description: successful operation + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + operationId: createUsersWithArrayInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + operationId: createUsersWithListInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + /user/login: + get: + tags: + - user + summary: Logs user into the system + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + style: form + explode: true + schema: + type: string + - name: password + in: query + description: The password for login in clear text + required: true + style: form + explode: true + schema: + type: string + responses: + 200: + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + style: simple + explode: false + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when toekn expires + style: simple + explode: false + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + 400: + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + operationId: logoutUser + responses: + default: + description: successful operation + /user/{username}: + get: + tags: + - user + summary: Get user by user name + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + style: simple + explode: false + schema: + type: string + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/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 + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + style: simple + explode: false + schema: + type: string + requestBody: + description: Updated user object + content: + application/json: + schema: + $ref: '#/components/schemas/User' + required: true + 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 + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + style: simple + explode: false + schema: + type: string + responses: + 400: + description: Invalid username supplied + 404: + description: User not found +components: + schemas: + Order: + title: Pet Order + 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 + description: An order for a pets from the pet store + example: + petId: 6 + quantity: 1 + id: 0 + shipDate: 2000-01-23T04:56:07.000+00:00 + complete: false + status: placed + xml: + name: Order + Category: + title: Pet category + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + description: A category for a pet + example: + name: name + id: 6 + xml: + name: Category + User: + title: a User + 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 + description: User Status + format: int32 + description: A User who is purchasing from the pet store + example: + firstName: firstName + lastName: lastName + password: password + userStatus: 6 + phone: phone + id: 0 + email: email + username: username + xml: + name: User + Tag: + title: Pet Tag + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + description: A tag for a pet + example: + name: name + id: 1 + xml: + name: Tag + Pet: + title: a Pet + required: + - name + - photoUrls + type: object + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + description: A pet for sale in the pet store + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 0 + category: + name: name + id: 6 + tags: + - name: name + id: 1 + - name: name + id: 1 + status: available + xml: + name: Pet + ApiResponse: + title: An uploaded response + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + description: Describes the result of uploading an image resource + example: + code: 0 + type: type + message: message + body: + type: object + properties: + name: + type: string + description: Updated name of the pet + status: + type: string + description: Updated status of the pet + body_1: + type: object + properties: + additionalMetadata: + type: string + description: Additional data to pass to server + file: + type: string + description: file to upload + format: binary + requestBodies: + UserArray: + description: List of user object + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + required: true + Pet: + description: Pet object that needs to be added to the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + api_key: + type: apiKey + name: api_key + in: header